How do you do your tests on your ASPNET Web API ?

post-thumb

Unit testing is the part of the development, to the point that legacy code is sometimes defined as code without unit test. 

Now, we know we have to create unit test, but often we come across situations that make unit test very tricky, such is the case of DOTNET Web API controllers. 

The main problem lies with the Request object in the API, this object requires quite a bit of effort to be mocked, I like the way AutoFixture leverages the generation of objects for me, it facilitates the maintenance of unit tests and test data as well.

Looking for ways to apply the same principle to the Request object with AutoFixture I ran into this thread in StackOverflow: https://stackoverflow.com/questions/19908385/automocking-web-api-2-controller, however, following it led me to generating a few classes that eventually I would have had to copy to every project I needed to test, and so I created the AutoFixture.AutoMoq.WebApi NUGET package.

https://github.com/delacruzjl/AutoFixture.AutoMoq.WebApi

After downloading the package to your project you just need to customize the fixture and just use .Create to create your system under test as you would normally would.  I prefer to create my fixture in the constructor because it makes it run one time and that's it, a static method to run at the beginning of the tests would do as well.

private readonly Fixture _fixture;
  
  public YourTestClassConstructor(){
    _fixture = new Fixture();
     _fixture.Customize(new ApiControllerConventions()); //Important!
  }
  ...
  
  //When instantiating your API controller system under test use
  _systemUnderTestAPIController = _fixture.Create<YourApiController>();

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.