Question

I am exploring CodeCamper project by JohnPapa on github https://github.com/johnpapa/CodeCamper. This is a ASP.Net SPA application and I am also working on similar project.

I interested to write some UnitTests for WebAPI controller. Controller contractor requires UnitofWork instanse and UnitofWork is initiate in Application_Start method.

When I run my UnitTest project UnitofWork object is null. How I can initiate UnitofWork from UnitTest project so that I can run my test methods. I hope make myself clear.

Here is a sample UnitTest method for following controller.

LookupsController.cs

UserControllerTest.cs

    [TestClass]
    public class UserControllerTest : ApiBaseController
    {
        [TestMethod]
        public void GetRoomsTest()
        {
            var controller = new LookupsController(Uow);
            var result = controller. GetRooms().Any();
            Assert.IsTrue(result);
        }
    }

Again why Uow is null? What should I do, so that I can write unit test methods for this type of project/architecture.

For more detail about code you can check github repo.https://github.com/johnpapa/CodeCamper

Was it helpful?

Solution

Use any mocking framework to create a fake/stub/mock for ICodeCamperUow (below I am using NSubstitute):

[TestMethod]
public void GetRoomsTest()
{
  // UOW we need to use
  var fakeUOW = Substitute.For<ICodeCamperUow>();

  // setting up room repository so that it returns a collection of one room
  var fakeRooms = Substitute.For<IRepository<Room>>();
  var fakeRoomsQueryable = new[]{new Room()}.AsQueryable();
  fakeRooms.GetAll<Room>().Returns(fakeRoomsQueryable);

  // connect UOW with room repository
  fakeUOW.Rooms.Returns(fakeRooms);

  var controller = new LookupsController(fakeUOW);
  var result = controller.GetRooms().Any();
  Assert.IsTrue(result);
}

Please consider reading The Art of Unit Testing which is a great book to learn about unit testing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top