ABP vNext 单元测试模拟HttpContext
1.Application.Tests的Module中注入
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddHttpContextAccessor();
}
2.TestBase注入ICurrentUser信息
[Dependency(ReplaceServices = true)]
public class FakeCurrentPrincipalAccessor : ThreadCurrentPrincipalAccessor
{
protected override ClaimsPrincipal GetClaimsPrincipal()
{
return GetPrincipal();
}
private ClaimsPrincipal GetPrincipal()
{
return new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim(AbpClaimTypes.UserId, "2e701e62-0953-4dd3-910b-dc6cc93ccb0d"),
new Claim(AbpClaimTypes.UserName, "admin"),
new Claim(AbpClaimTypes.Email, "admin@abp.io"),
new Claim(AbpClaimTypes.Name, "admin")
}
)
);
}
}
3.Application.Tests的Module中使用
public class PointInspectionTopicService_Test : EquipApplicationTestBase
{
private readonly IPointInspectionTopicService _pointInspectionTopicService;
private readonly IHttpContextAccessor _contextAccessor;
public PointInspectionTopicService_Test()
{
_contextAccessor = ServiceProvider.GetService<IHttpContextAccessor>();
_pointInspectionTopicService = GetRequiredService<IPointInspectionTopicService>();
}
[Fact]
public async Task Test_CreateAsync_OK()
{
var queryColl = new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>();
var moqContext = new Mock<HttpContext>();
var moqRequest = new Mock<HttpRequest>();
moqRequest.Setup(p => p.Query).Returns(new QueryCollection(queryColl));
moqContext.Setup(p => p.Request).Returns(moqRequest.Object);
_contextAccessor.HttpContext = moqContext.Object;
await _pointInspectionTopicService.CreateAsync(new()
{
Name = "测试新增点检项目",
Description = "测试新增点检项目",
JobGuide = "测试新增点检项目指南",
IsEnabled = true,
Status = 1
});
var entity = await _pointInspectionTopicService.GetListWithDetailsAsync(new()
{
PageIndex = 1,
PageSize = 10,
});
entity.TotalNumber.ShouldBe(2);
}
}
4 .Application中方法
public async Task<PointInspectionTopicRes> GetListWithDetailsAsync(PagePointInspectionTopicReq input)
{
var dyParams = HttpContext.Request.Query.GetDynamicParams();
var topicCount = await _pointInspectionTopicRepository.WithDetailsAsync(s => s.PointInspectionDetails);
topicCount = dyParams.QueryKeys.IsNullOrWhiteSpace() ? topicCount : topicCount.Where(dyParams.QueryKeys, dyParams.QueryValues.ToArray());
var topic = topicCount.Skip(input.SkipCount).Take(input.PageSize).ToList();
return new PointInspectionTopicRes(topicCount.Count(), ObjectMapper.Map<List<PointInspectionTopic>, List<PointInspectionTopicInfoRes>>(topic));
}