I have the following C# method:
public class MyClass {
public bool foo(Dependency dependency)
{
bool result = false;
var metadata = dependency.dependencyMethod();
if(metadata.containsProperty()){
// doSomething
} else
{
// doSomethingElse
}
return result;
}
}
I'd like to capture the value that gets returned by the dependency.dependencyMethod()
(which is essentially the value of the method's metadata
variable).
Basically, I'd like to assert that the value returned from dependency.dependencyMethod()
matches the mocked response value I defined for it (described below):
//Arrange
MyClass myClass = new MyClass(); // System Under Test
Mock<Dependency> dependencyMock = new Mock<Dependency>(); //Mocking dependency
// Mocking the behavior of the dependencyMock to return a pre-defined value when invoked
dependencyMock
.Setup(d => d.dependencyMethod())
.Returns("dummyMetadata");
// How do we capture the value returned when `dependencyMock.dependencyMethod()` gets invoked?
dependencyMock
.Setup(d => d.dependencyMethod()) // When invoking the `dependencyMethod()`
.Callback(); // <--- How to Capture the value returned when d.dependencyMethod() gets called, and assert that it matches "dummyMetaData"?
// Act
myClass.foo(dependencyMock);
Is there any way I can capture the value that gets returned from dependencyMock.dependencyMethod()
?
Yes, the return value of dependencyMock.dependencyMethod()
is a mocked one. Regardless, I'd like to capture this returned value, and confirm that the pre-defined mocked response is, in fact, being returned.
CodePudding user response:
You have to pass dependencyMock.Object
to the foo method. You can verify the method wan called with
dependencyMock.Verify(mock => mock.dependencyMethod(), Times.Once());
It will always return the value that you set in the
dependencyMock.Setup(d => d.dependencyMethod()).Returns("dummyMetadata");
line. In your act step call some method that uses the passed in "dummyMetadata
" value, and verify that. Or you can mock something from which the dependencyMethod()
calculates it return value and check that.
CodePudding user response:
In your unit test call dependencyMock.dependencyMethod() and assert that the return value equals "dummyMetadata". Put "dummyMetadata" in a variable or constant so you can refer to it both places.
You are testing your Mock setup at this point so the above will verify you have it setup as desired. It doesn't make any sense to try and test the return value inside your class under test MyClass as that is just proving Mock works properly. If you want to verify one time that the value returned inside MyClass is what is mocked just use the debugger to verify.
I would argue that this assertion is not necessary but it is your choice to do if you want.