27

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.

Peter Kelly
  • 14,253
  • 6
  • 54
  • 63

2 Answers2

29

"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);
Fischermaen
  • 12,238
  • 2
  • 39
  • 56
  • 1
    For this example it would be better to mock out DateTime with an interface like IDateTimeProvider. Then you can make several unit tests for this. Unit Tests should not have different behavior depending on time! – maracuja-juice Mar 06 '19 at 20:29
2

With this method you can configure your mocked object's behavior when the condition set in Mock<T>.When(...) evaluates to true. This enables your mocked object to react differently depending on the given condition.

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108