0

I am not much comfortable to write unit test. So sorry for asking basic questions.

Here is commandhandler

ICalculateAge CalculateAge { get; set; }

public UpdateAgeCommandHandler(ICalculateAge calculateAge)
{
    this.CalculateAge = calculateAge;
}

I want to unit test this, so I tried below in of cs file in my test project:

UpdateAgeCommandHandler cmd1 =  new UpdateAgeCommandHandler());

But its not working because I am not passing Interface. How do I pass this interface?

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
James
  • 1,827
  • 5
  • 39
  • 69

1 Answers1

1

You cannot pass interface as interface is just meant for standardization.

You should pass the implementation of interface. Implementation means the class which implements ICalculateAge.

Documentation on interface

This blog explains exact same scenario by taking an example. It may be helpful for you.

In this blog, they are using Moq framework to mock the interface. They are also setting up what should be returned when a method is called on the mock object.

var mockFinancialService = new Mock<IFinancialService>();
mockFinancialService.Setup(x => 
     x.GetFinancialScore(balance)).Returns(expected);

Then they are passing that mocked object to the the class instead of interface.

var account = new BankAccount(mockFinancialService.Object);
account.PutMoney(balance);

All the above steps are arranging all the stuff required for unit test. Next, you just have to call the actual method and verify the result.

// Act
string actual = account.GetFinancialScore();

// Assert
Assert.AreEqual(actual, expected);

Similar to this you will need to setup mock from your interface, provided you do not want to test the actual implementation of interface.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37