Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moq objects Returns method, should return a null object

I'm developing a Web API, and one of the test I came up with is that, if client makes a GET operation with a Physical Test ID (Physical Test is the resource I'm looking for) and that physical test is not found, the web API should return a 404 status.

Now, I'm using moq framework for my tests and I have the following code:

[TestMethod] public void then_if_physical_test_not_found_return_not_found_status() {     var unitOfWork = new Mock<IUnitOfWork>();     var repository = new Mock<IRepository<PhysicalTest>>();     repository.Setup(r => r.FindById(It.IsAny<int>())).Returns();     unitOfWork.Setup(m => m.PhysicalTests).Returns(repository.Object);     var pt = new PhysicalTestResource(unitOfWork.Object);     HttpResponseMessage<PhysicalTest> response = pt.GetPhysicalTest(43);     Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode) } 

I need the Returns() method to return a null object, which is going to be what the actual API method would return if the resource is not found.

I tried sending null as a parameter in the Returns() method but had no success.

like image 654
Daniel Avatar asked Oct 27 '11 17:10

Daniel


People also ask

What can be mocked with MOQ?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.

What is MOQ in unit testing C#?

Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.

What is mock setup?

With mocks, you can set up the object, including giving parameters and return values on method calls and setting properties. You can also verify that the methods you set up are being called in the tested code. This ensures that the flow of the program is as expected.


2 Answers

You don't indicate what the error was, but this should work:

unitOfWork.Setup(m => m.PhysicalTests).Returns((IRepository<PhysicalTest>)null); 

I suspect you tried to call it with Returns(null), which causes the compiler to complain since Returns is overloaded and it doesn't know which method should be called. Casting to a specific type removes the ambiguity.

like image 183
Jeff Ogata Avatar answered Sep 29 '22 16:09

Jeff Ogata


rt is a return type of method: FindById

repository.Setup(r => r.FindById(It.IsAny<int>())).Returns(Task.FromResult((rt)null));

like image 21
Radhika Patwari Avatar answered Sep 29 '22 17:09

Radhika Patwari