相关疑难解决方法(0)

Moq IServiceProvider/IServiceScope

我正在尝试创建一个模拟(使用Moq),IServiceProvider以便我可以测试我的存储库类:

public class ApiResourceRepository : IApiResourceRepository
{
    private readonly IServiceProvider _serviceProvider;

    public ApiResourceRepository(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
        _dbSettings = dbSettings;
    }

    public async Task<ApiResource> Get(int id)
    {
        ApiResource result;

        using (var serviceScope = _serviceProvider.
            GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
            result = await
                context.ApiResources
                .Include(x => x.Scopes)
                .Include(x => x.UserClaims)
                .FirstOrDefaultAsync(x => x.Id == id);
        }

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建Mock对象的尝试如下:

Mock<IServiceProvider> serviceProvider = new Mock<IServiceProvider>();

serviceProvider.Setup(x => x.GetRequiredService<ConfigurationDbContext>())
    .Returns(new ConfigurationDbContext(Options, StoreOptions));

Mock<IServiceScope> serviceScope = new Mock<IServiceScope>(); …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq .net-core asp.net-core

18
推荐指数
5
解决办法
7558
查看次数

如何单元测试HttpContext.SignInAsync()?

SignInAsync()源代码

我遇到了单元测试的一些问题.

  1. DefaultHttpContext.RequestServicesnull
  2. 我试图创建AuthenticationService对象,但我不知道要传递什么参数

我该怎么办?如何进行单元测试HttpContext.SignInAsync()

正在测试的方法

public async Task<IActionResult> Login(LoginViewModel vm, [FromQuery]string returnUrl)
{
    if (ModelState.IsValid)
    {
        var user = await context.Users.FirstOrDefaultAsync(u => u.UserName == vm.UserName && u.Password == vm.Password);
        if (user != null)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName)
            };
            var identity = new ClaimsIdentity(claims, "HappyDog");

            // here
            await HttpContext.SignInAsync(new ClaimsPrincipal(identity));
            return Redirect(returnUrl ?? Url.Action("Index", "Goods"));
        }
    }
    return View(vm);
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过的.

[TestMethod]
public async Task LoginTest()
{
    using …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing .net-core asp.net-core asp.net-core-2.0

12
推荐指数
1
解决办法
2845
查看次数