Question

I am currently writing unit tests and mocking a dependency using Moq framework. In doing this I have created a Mock like so:

Mock<ITraceProvider> traceProviderMock = new Mock<ITraceProvider>();
traceProviderMock.Setup(x => x.GetTraceContext(It.IsAny<string>())).Returns("test");
ITraceProvider traceObj = traceProviderMock.Object;

However later on I want to modify the behaviour of the mock a little more so I call Setup on the Mock object again:

traceProviderMock.Setup(x => x.GetTracer(It.IsAny<string>())).Returns("tracer");

Now without calling the traceProviderMock.Object again, will this new mock behaviour reflected in traceObj? That is what I would like to be the case.

This definitely works for the Verify() method but doesn't appear to for the Setup method.

The reason I want to do this, is due to the fact I have constructed a full dependency graph in the Test Setup method using a mocked dependency. I just want to change the behaviour of one of the mocked dependencies for my specific test. Subsequent tests would also apply their own specialisations to the mocked dependency.

Was it helpful?

Solution

This behaviour actually works as I expected it to. Due to an issue with my test, I was not actually calling the newly mocked method. This mislead me to believing the mocking framework was not behaving.

To summarise, you can change the mock after .Object has been called and the changes will be reflected in the mocked object instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top