Reputation: 111
I am a totally newbie to Mediator pattern and Moq. I have an API controller that has an async task method and want to mock this method
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class UsersController : UsersControllerBase
{
private readonly IMediator _mediator;
public UsersController(IMediator mediator)
{
this._mediator = mediator;
}
[HttpGet("GetUsers")]
public async Task<ActionResult<ICollection<User>>> GetUsers(CancellationToken cancellationToken)
{
var result = await _mediator.Send(new UserGetRequest(),
cancellationToken).ConfigureAwait(false);
return DataOrProblem(result);
}
}
I am trying to create or mock this method and not sure how to do it? Here is what I have tried
public class GetUsersTest
{
//Arrange
private readonly Mock<IMediator> _mediator = new Mock<IMediator>();
private readonly Mock<UsersController> _sut;
public GetUsersTest()
{
_sut = new Mock<UsersController>(_mediator);
}
}
Upvotes: 0
Views: 650
Reputation: 247531
If the controller is the subject under test then do not mock it. Create an actual instance, injecting the mocked mediator.
public class UsersControllerTest {
public async Task GetUsersTests() {
//Arrange
Mock<IMediator> mediator = new Mock<IMediator>();
UsersController sut = new UsersController(mediator.Object);
//... setup the behavior of the mocked mediator
ICollection<User> expected = //...provide fake data here
mediator
.Setup(s => s.Send<UserGetRequest>(It.IsAny<UserGetRequest>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(expected);
//Act
ActionResult<ICollection<User>> result = await sut.GetUsers(CancellationToken.None);
//Assert
//assert the expected behavior with what actually happened
}
}
Upvotes: 1