When
Use When to add a conditional guard to an arrangement. The arrangement applies only when the condition you provide returns true. If the condition is false, JustMock skips the arrangement and the call is handled by the next matching arrangement or the mock's default behavior.
Use When when the condition depends on external state rather than the method's own arguments. For argument-based conditions, use Matchers instead. You can also combine When with IgnoreInstance() or IgnoreArguments() on the same arrangement.
To understand how to use the When method, check the next examples:
How It Works
Let's assume we have the following interface:
public interface IFoo
{
bool IsCalled();
string Prop { get; set; }
}Using JustMock, we can set a certain arrangement to be used only if another expectations are met. The below test method is a demonstration of this. The IsCalled function is arranged to return true only if Prop is equal to "test".
[TestMethod]
public void IsCalled_ShouldReturnTrue_WithMockedDependencies()
{
// Arrange
var foo = Mock.Create<IFoo>();
Mock.Arrange(() => foo.Prop).Returns("test");
Mock.Arrange(() => foo.IsCalled()).When(() => foo.Prop == "test").Returns(true);
// Assert
Assert.IsTrue(foo.IsCalled());
}How It Helps
There are situations where you need to make an arrangement that will only work when a certain condition is true. If the condition is related to that member's input arguments, you can use Matchers. However, if the condition is not related to them, you can achieve the desired behavior by using the When method.
Look at the following interface:
public interface IRequest
{
string Method { get; set; }
string GetResponse();
}In the test, we will check if GetResponse() has been called once when Method == "GET" and once more when Method == "POST". Note that, the Method property is unrelated to the GetResponse() method.
[TestMethod]
public void ShouldAssertThatSUTCallsGetResponseWithBothGetAndPostMethods()
{
// Arrange
var mock = Mock.Create<IRequest>();
Mock.Arrange(() => mock.GetResponse()).When(() => mock.Method == "GET").OccursOnce();
Mock.Arrange(() => mock.GetResponse()).When(() => mock.Method == "POST").OccursOnce();
// Act
mock.Method = "GET";
mock.GetResponse();
mock.Method = "POST";
mock.GetResponse();
// Assert
Mock.Assert(mock);
}