0
如何設置Mock<UserManager<ApplicationUser>> _userManager
所以_userManager.FindByIdAsync(userId)
去ApplicationDbContext,發現了被標識這樣_context.Users.SingleOrDefault(u=>u.Id == userId)
用戶?如何設置模擬<的UserManager <TUser >>
我的代碼:
[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;
}
}
我該如何做到這一點?
在當前狀態下的問題是,目前還不清楚,因爲它是不完整的。閱讀[問],然後提供[mcve],可用於更好地理解您的問題。 – Nkosi
Hi @Jones,給我們和你的測試代碼的例子或完全粘貼它,我們將能夠幫助你走向正確的方向。回答這個意見,我會看看(順便說一句,你是否熟悉Moq圖書館?) – Juan