Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a new object for each Returns() in NSubstitute

I have created a substitute which mocks a web service interface for my unit testing which includes the following method definition:

public Message Invoke(Message input)

This method is called using:

var reply = webService.Invoke(messageObject)

When I make multiple calls to the same method, it is throwing the following exception:

System.InvalidOperationException : This message cannot support the operation because it has been read.

Here is my Nsubstitute mock code:

outputMessageObj = GetResponseMessage()
wsMock.Invoke(Arg.Any<Message>()).Returns(outputMessageObj)

How do I ensure that a new outputMessage object is returned each time the call is made?

like image 569
semantic_c0d3r Avatar asked Jan 03 '18 21:01

semantic_c0d3r


People also ask

How do we set a return value for a method call on a substitute?

To set a return value for a method call on a substitute, call the method as normal, then follow it with a call to NSubstitute's Returns() extension method. var calculator = Substitute. For<ICalculator>(); calculator.

What is NSubstitute?

NSubstitute is a great library for mocking objects for Test Driven Development (TDD) in . NET.


1 Answers

Got it, just use a lambda to invoke a method which returns a new Message object each time:

wsMock.Invoke(Arg.Any<Message>()).Returns(x => GetResponseMessage())
like image 142
semantic_c0d3r Avatar answered Oct 13 '22 00:10

semantic_c0d3r