如何设置Mock<UserManager<ApplicationUser>> _userManager
所以_userManager.FindByIdAsync(userId)
转到ApplicationDbContext并通过ID查找用户_context.Users.SingleOrDefault(u=>u.Id == userId)
?
我的代码:
[TestClass]
public class AccountControllerTest
{
private ApplicationDbContext _context;
private Mock<UserManager<ApplicationUser>> _userManager;
private IHostingEnvironment _enviroment;
private Referrals _referrals;
private Mock<IEmailSender> _emailSender;
private Mock<IUserNameGenerator> _userNameGenerator;
private Mock<IUrlHelper> _urlHelper;
private Mock<SignInManager<ApplicationUser>> _signInManager;
private TimeSpan _startTrialTime;
[TestInitialize]
public void Init()
{
_userManager = UserManagerAndDbMocker.GetMockUserManager();
_context = UserManagerAndDbMocker.ContextInMemoryMocker();
_enviroment = new HostingEnvironment() { EnvironmentName = "Development" };
_referrals = new Referrals(_context, _userManager.Object);
_emailSender = new Mock<IEmailSender>();
_userNameGenerator = new Mock<IUserNameGenerator>();
_urlHelper = new Mock<IUrlHelper>();
_signInManager = new Mock<SignInManager<ApplicationUser>>();
UserManagerSetup();
}
private void UserManagerSetup()
{
_userManager.Setup(um => um.CreateAsync(
It.IsAny<ApplicationUser>(),
It.IsAny<string>()))
.Returns(Task.FromResult(IdentityResult.Success));
_userManager.Setup(um => um.ConfirmEmailAsync(
It.IsAny<ApplicationUser>(),
It.IsAny<string>()))
.Returns(
Task.FromResult(IdentityResult.Success));
_userManager.Setup(um => um.FindByIdAsync(It.IsAny<string>()));
}
我坚持嘲笑FindByIdAsync
。我希望在测试_userManager.FindById(userId)
时返回_context.Users.SingleOrDefault(u=>u.Id == userId)
。
public static class UserManagerAndDbMocker
{
public static Mock<UserManager<ApplicationUser>> GetMockUserManager()
{
var userStoreMock = new Mock<IUserStore<ApplicationUser>>();
return new Mock<UserManager<ApplicationUser>>(
userStoreMock.Object, null, null, null, null, null, null, null, null);
}
public static ApplicationDbContext ContextInMemoryMocker()
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseInMemoryDatabase();
var context = new ApplicationDbContext(optionsBuilder.Options);
return context;
}
}
我怎样才能做到这一点?
答案 0 :(得分:1)
如果我理解你的问题,这应该适合你:
_userManager
.Setup(um => um.FindByIdAsync(It.IsAny<string>()))
.Returns( (string userId) => _context.Users.SingleOrDefault(u => u.Id == userId));
在Returns方法中,您可以指定使用实际输入参数的lambda。