tmp dev
tmp dev

Reputation: 9193

dotnet core web app unit test controller

I have a dotnetcore web app and am looking to unit test the controllers. How do I get about this?

I have a simple controller that looks like this

public class ConversionController : Controller {
    private readonly INumberService _numberService;

    public ConversionController(INumberService numberService)
    {
        this._numberService = numberService;
    }

    // GET http://localhost:9789/api/conversion/123
    [HttpGet("{number}")]
    public string Get(decimal number)
    {
        return _numberService.ConvertToWords(number);
    }
}

The INumberService is passed in as a parameter. How do I unit test this?

Upvotes: 2

Views: 331

Answers (1)

Nkosi
Nkosi

Reputation: 247088

By mocking the interface/dependency and exercising an isolated unit test for the Get method. You could either create your own mock or use a mocking framework to mock the dependency. From there assert that the system under test behaves as expected.

For example the following simple test uses Moq to mock the dependency and test the Get method.

[TestMethod]
public void ConversionController_Get_Should_Return_Five() {
    //Arrange
    var number = 5;
    var expected = "five";
    var mock = new Mock<INumberService>();
    mock.Setup(_ => _.ConvertToWords(number)).Returns(expected);
    var sut = new ConversionController(mock.Object);

    //Act
    var actual = sut.Get(number);

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

You should also take some time and check the documentation provided

Unit Testing in .NET Core

Upvotes: 1

Related Questions