Reputation: 3450
I have void method:
this._dispatcher.PushAsync(handler, cmd);
After execution I have changed property of cmd
:
cmd.Result = userId;
How can I set property value after execution void method in unit test?
I'm trying something like that:
_dispatcher = new Mock<IDispatcher>();
_a = new Mock<SaveUserCmd>();
_dispatcher
.Setup(r => r.PushAsync(_cmdHandler, this._cmd))
.Callback(() => _a.SetupProperty(y => y.Result == this._response));
But it shows...
(Error: Expression is not a property access:
y => y.Result == this._response
).
SaveUserCmd:
public class SaveUserCmd
{
public string FirstName { get; set; }
public string LastName { get; set; }
public object Result { get; set; }
}
IDispatcher:
public interface IDispatcher
{
Task PushAsync<TCommand>(ICommandHandlerAsync<TCommand> commandHandlerAsync, TCommand message);
}
Upvotes: 2
Views: 645
Reputation: 247471
First you want to assign a value in the callback. ==
is not assigning a value it is an equality comparison.
Second no need to mock the model. Just create an instance and use that. You can always access it in the callback via parameters.
Third as the method to be mocked is async you need to return a task so that code can flow to completion.
//Arrange
var dispatcher = new Mock<IDispatcher>();
var cmd = new SaveUserCmd();
var userId = "some value here";
dispatcher.Setup(r => r.PushAsync(_cmdHandler, cmd))
.Callback((ICommandHandlerAsync<SaveUserCmd> h, SaveUserCmd c) => c.Result = userId))
.Returns(Task.FromResult((object)null));
Upvotes: 2
Reputation: 388233
_a.SetupProperty
will set up the property of the mock _a
which is not what you want to do (in general, initializing mocks later is never the correct approach). Instead, you just want to assign a value to a property of the actual object.
You can easily do that using .Callback()
which also has overloads that will give you the exact instance that was passed to the mocked method call:
_dispatcher
.Setup(r => r.PushAsync(It.IsAny<ICommandHandlerAsync<SaveUserCmd>>(), It.IsAny<SaveUserCmd>()))
.Callback((handler, cmd) => {
cmd.Result = "static result";
});
This set up method call now accepts any valid arguments and just sets the result of the passed command to a fixed result. So you can easily test whether the actually tested thing calls the dispatcher object properly.
Upvotes: 0