Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter Mock<IType> object after .Object property has been called

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.

like image 678
andrew_scfc Avatar asked Sep 04 '13 10:09

andrew_scfc


1 Answers

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.

like image 74
andrew_scfc Avatar answered Oct 11 '22 12:10

andrew_scfc