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.
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.
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.
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.
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.
"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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With