Getting an NMock expectation to return a new object based on received arguments

StackOverflow https://stackoverflow.com/questions/14850097

  •  09-03-2022
  •  | 
  •  

Domanda

NMock3 is my mocking framework of choice, but I'm struggling to make it do what I want.

What I need is for a new object to be constructed and returned as part of an expectation, based on some of the parameters that are received when the expectation is met.

For example:

var mockFactory = new MockFactory();
var mockA = mockFactory.CreateMock<ObjectA>();
mockA.Expects.One.Method(c => c.BuildObjectB(null))
  .With(Is.TypeOf(typeof(string)))
  .WillReturn(new ObjectB(<?>));

When newing up ObjectB in WillReturn, how can I access the arguments that the expectation received? Is this even possible with NMock3?

Thanks!

È stato utile?

Soluzione

I do not think the NMock3 library allows you to do this. The documentation is sparse but I've looked through NMock3's Acceptance Tests and cannot find one that does something like this.

I do not think that this is a very bad thing. Unit tests are generally deterministic so will know ahead of time what the value of the String will be. Unit tests are the one place where repeating yourself is a good thing. It makes the test simpler and more readable. So in your example I'd say go for the simple but utterly readable

var mockFactory = new MockFactory();
var mockA = mockFactory.CreateMock<ObjectA>();
mockA.Expects.One.Method(c => c.BuildObjectB("Frank")).WillReturn(new ObjectB("Frank"));

I can think of some (rare) nondeterministic cases where for instance a DateTime is returned and you do not know ahead of time which one it will be. Or perhaps the function will get called a great many times with different arguments. In those cases, you could use a simple stub that keeps track of how many times it got called.

Altri suggerimenti

You can use Collect.MethodArgument:

var mockFactory = new MockFactory();
var mockA = mockFactory.CreateMock<ObjectA>();
mockA.Expects.One.Method(c => c.BuildObjectB(null))
  .With(Is.TypeOf(typeof(string)))
  .WillReturn(Collect.MethodArgument<string>(0, delegate(string myString) { new ObjectB(myString); }));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top