Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Moq When(Func<bool>) method

Tags:

c#

moq

I can't find an example of the usage of the When method in Moq

When(Func<bool> condition); 

What is the purpose/usage of the method? Please give a code sample demonstrating a scenario where it would be useful.

like image 498
Peter Kelly Avatar asked Oct 14 '11 11:10

Peter Kelly


People also ask

How do you mock a method in Moq?

First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.

What can be mocked with Moq?

Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation. Moq is a mock object framework for . NET that greatly simplifies the creation of mock objects for unit testing.

Can you mock a class 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. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

What is Moq mocking framework?

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.


1 Answers

"When" gives you the option to have different setups for the same mocked object, depending on whatever you have to decide. Let's say you want to test a format provider you have written. If the program (= test) runs in the morning a certain function call should return null; in the afternoon a certain value. Then you can use "When" to write those conditional setups.

var mockedService = new Mock<IFormatProvider>();  mockedService.When(() => DateTime.Now.Hour < 12).Setup(x => x.GetFormat(typeof(string))).Returns(null); mockedService.When(() => DateTime.Now.Hour >= 12).Setup(x => x.GetFormat(typeof(string))).Returns(42); 
like image 174
Fischermaen Avatar answered Sep 24 '22 07:09

Fischermaen