使用Mediator对ASP.Net核心进行单元测试时出现问题



我使用的是ASP.Net Core 3.1存储库模式和使用Dapper的工作单元。我已经使用中介作为

using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace TaskManagementApp.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ApiController : ControllerBase
{
private IMediator _mediator;
protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}
}

我面临的问题是如何编写单元测试来设置HttpContext.RequestServices.GetService 的值

这是我的控制器要进行单元测试

namespace OneCubeCoaching.API.WebApi.Controllers
{
[Route("api/[controller]")]
public class ContactController : BaseApiController
{
[Authorize]
[HttpGet("GetAll")]
public async Task<IActionResult> Index()
{
return Ok(await Mediator.Send(new GetAllClientQuery()));
}
}
}

只需依赖构造函数中的IMediator。

假设你的代码意味着ApiController实际上是BaseApiController(根据你的第二个代码段(,这样的东西会起作用:

[Route("api/[controller]")]
[ApiController]
public class BaseApiController : ControllerBase
{
protected ApiController(IMediator mediator)
{
_mediator = mediator;
}
protected IMediator {get; private set;}
}

然后你的ContactController可以将IMediator传递到基地:

[Route("api/[controller]")]
public class ContactController : BaseApiController
{
public ContactController (IMediator mediator) 
:base(mediator)
[Authorize]
[HttpGet("GetAll")]
public async Task<IActionResult> Index()
{
return Ok(await Mediator.Send(new GetAllClientQuery()));
}
}

现在,您可以像往常一样模拟IMediator了。

相关内容

  • 没有找到相关文章

最新更新