Question

With moq, you can call Setup on the same method multiple times with different conditions regarding the input:

// Arrange
Mock<IObject> stub = new Mock<IObject>();
stub.Setup(method => method.Foo(It.IsAny<int>())
    .Returns<int>(value => value);
stub.Setup(method => method.Foo(It.Is<int>(t => t == 100)
    .Returns<int>(value => value * 1.10);

var sut = new TestedObject(stub.Object);

// Act
var actual = sut.Bar();
...

...and so on. In this case, the Foo method takes an integer and depending on the value passed determines the implementation of the method.

Is there a way to accomplish this with Visual Studio fakes? The code would look something like this:

// Arrange
var stub = new StubIObject
{
    Foo = (value) => value,    // This covers the default case (It.IsAny<T>)
};

var sut = new TestedObject(stubIObject);

// Act
var actual = sut.Bar();

but how would you setup the other conditional cases?

EDIT: I should mention I do realize this is a strange setup, normally you wouldn't test different implementations of a stub in one unit test. This is a purely academic question - I wouldn't put this type of code in a unit test...probably.

Was it helpful?

Solution

Because with Fakes you can basically provide delegates to act as implementation of the generated stub methods you can put any conditional logic inside that delegate.

In your case the following setup if equivalent with the moq example:

var stub = new StubIObject
{
    Foo = (value) => 
       {
           if (value == 100)  
              // This covers the case (It.Is<int>(t => t == 100))
              return value * 1.10;
           return value;    // This covers the default case (It.IsAny<T>)
        }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top