Search code examples
visual-studioasp.net-web-apiautomated-testsxunittestcase

How to write test code for Web API in Visual Studio?


I'm a bit new to test project. I currently have a web api project which contains Get, Put, Post and Delete methods. When comes to writing test cases, I'm confused. Should I write test code to test the Http URL?

My web api code:

    // GET api/values/5
    [HttpGet("{id}")]
    public IActionResult Get(string id)
    {
        using (var unitOfWork = new UnitOfWork(_db))
        {
            var r = unitOfWork.Resources.Get(id);

            unitOfWork.Complete();

            Models.resource result = ConvertResourceFromCoreToApi(r);

            if (result == null)
            {
                return NotFound();
            }
            else
            {
                return Ok(result);
            }
        }
    }

And in my test project, I kind of stuck here. We are using Xunit. How to write test code to test the Get method? Or should I write code to test the URL api/values/5 instead, but how?

    [Fact]
    public void GetTest()
    {
        using (var unitOfWork = new UnitOfWork(new MockDatabase()))
        {

        }
    }

Any help would be appreciated.


Solution

  • You need to make a couple of changes before you can really unit test your controller. You need to pass an instance of your UnitOfWork class into the controller in its constructor. Then your controller method code becomes:

    // GET api/values/5
    [HttpGet("{id}")]
    public IActionResult Get(string id)
    {    
        var r = unitOfWork.Resources.Get(id);
    
        unitOfWork.Complete();
    
        Models.resource result = ConvertResourceFromCoreToApi(r);
    
        if (result == null)
        {
            return NotFound();
        }
        else
        {
            return Ok(result);
        }
    

    Then in your unit tests you do this:

    [Fact]
    public void GetTest()
    {
        // Arrange
        // You really want to mock your unit of work so you can determine
        // what you are going to send back
        var unitOfWork = new MockUnitOfWork();
        var systemUnderTest = new Controller(unitOfWork);
        system.Request = new HttpRequestMessage();
    
        // Act
        var result = systemUnderTest.Get(1);
    
        // Assert
        // Here you need to verify that you got back the expected result
    }
    

    Injecting the UnitOfWork class into the controller is probably another question. Mark Seemann has an excellent post on the subject, but it might be a little advanced. There are a number of different ways to accomplish that with simpler (but maybe not as robust methods). Google is your friend with that. But if you have questions, post another question.

    Hope that helps.