[英]MediatR and CQRS testing. How to verify that handler is called?
I am currently trying to implement MediatR
in my project covering with tests.我目前正在尝试在包含测试的项目中实施
MediatR
。 I want to cover if handler's Handle
is called when sending a request.我想介绍在发送请求时是否调用了处理程序的
Handle
。
I have this query我有这个查询
public class GetUnitsQuery : IRequest<List<UnitResponse>>
{
}
Handler:处理程序:
public class GetUnitsHandler : IRequestHandler<GetUnitsQuery, List<UnitResponse>>
{
readonly IUnitRepository UnitRepository;
readonly IMapper Mapper;
public GetUnitsHandler(IUnitRepository unitRepository, IMapper mapper)
{
this.UnitRepository = unitRepository;
Mapper = mapper;
}
public async Task<List<UnitResponse>> Handle(GetUnitsQuery request, CancellationToken cancellationToken)
{
return Mapper.Map<List<UnitResponse>>(UnitRepository.GetUnits());
}
}
Send request from the controller:从 controller 发送请求:
var result = await Mediator.Send(query);
Any ideas how to test if a Handler
is called when specified with a specific Query
using MoQ
?任何想法如何在使用
MoQ
使用特定Query
指定时测试是否调用了Handler
程序?
I have not used MoQ to check the Received calls to a specific handler.我没有使用 MoQ 来检查收到的对特定处理程序的调用。 However if I would use Nsubsitute and SpecFlow, I would do something like this in my test.
但是,如果我使用 Nsubsitute 和 SpecFlow,我会在测试中执行类似的操作。
var handler = ServiceLocator.Current.GetInstance<IRequestHandler<GetUnitsQuery, List<UnitResponse>>>();
handler.Received().Handle(Arg.Any<GetUnitsQuery>(), Arg.Any<CancellationToken>());
Like others said in the comments, you don't need to test the internals of Mediator.就像其他人在评论中所说的那样,您不需要测试 Mediator 的内部结构。
Your test boundary is your application, so assuming a controller along the lines of:您的测试边界是您的应用程序,因此假设 controller 沿线:
public class MyController : Controller
{
private readonly IMediator _mediator;
public MyController(IMediator mediator)
{
_mediator = mediator;
}
public async IActionResult Index()
{
var query = new GetUnitsQuery();
var result = await Mediator.Send(query);
return Ok(result);
}
}
I would verify Mediator is called like this:我会验证 Mediator 是这样调用的:
public class MyControllerTests
{
[SetUp]
public void SetUp()
{
_mockMediator = new Mock<IMediator>();
_myController = new MyController(_mockMediator.Object)
}
[Test]
public async void CallsMediator()
{
// Arranged
_mockMediator.SetUp(x=> x.Send(It.IsAny<GetUnitsQuery>()))
.Returns (new List<UnitResponse>());
// Act
await _myController.Index();
// Assert
_mockMediator.Verify(x=> x.Send(It.IsAny<GetUnitsQuery>()), Times.Once);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.