【发布时间】:2017-05-14 10:45:48
【问题描述】:
我有以下接口及其存储库类
界面
public interface IIdentityRepository
{
bool CreateUser(ApplicationUser user, string password);
}
存储库
public class IdentityRepository : IIdentityRepository
{
ApplicationDbContext dbContext;
public IdentityRepository()
{
dbContext = new ApplicationDbContext(); // if none supplied
}
public bool CreateUser(ApplicationUser user, string password)
{
var userManager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(dbContext));
var idResult = userManager.Create(user, password);
return idResult.Succeeded;
}
}
public class UserManager : UserManager<ApplicationUser>
{
public UserManager()
: base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
{
}
}
这是我正在尝试为CreateUser 方法编写的测试类
在这种方法中,我使用AppplicationUser 作为我的模型。
[TestClass]
public class IdentityRepositoryTest
{
private IdentityRepository _identitityRepo;
private Mock<IIdentityRepository> _identitityRepository;
private List<ApplicationUser> _users;
// initialize the test class
[TestInitialize]
public void TestSetup()
{
_identitityRepository = new Mock<IIdentityRepository>();
_users = new List<ApplicationUser>();
_identitityRepository.Setup(m => m.CreateUser(It.IsAny<ApplicationUser>())).Callback<ApplicationUser>(c => _users.CreateUser(c));
_identitityRepo = new IdentityRepository();
}
#region Users
// check valid number of user/s(1) existing in current DB
[TestMethod]
public void IsValidtNumberofUsersExist()
{
// Arrange
_users.Add(new ApplicationUser { UserName = "Kez" , Email = "kez@gmail.com" });
// Act
var result = _identitityRepo.GetAllUsers();
Assert.IsNotNull(result);
// Assert
var numberOfRecords = result.ToList().Count;
Assert.AreEqual(1, numberOfRecords);
}
#endregion
}
但是在这里我遇到了以下编译时错误
编辑:
一旦我将错误行更改为以下错误就消失了。
_identitityRepository.Setup(m => m.CreateUser(It.IsAny<ApplicationUser>(),"password")).Callback<ApplicationUser>(c => _users.Add(c));
但是当我运行这个测试时,我得到了以下错误
结果信息:初始化方法 ProjectName.UnitTest.Common.IdentityRepositoryTest.TestSetup 抛出 例外。 System.ArgumentException:System.ArgumentException:无效 打回来。使用参数(ApplicationUser,String)设置方法 无法调用带参数的回调 (ApplicationUser)..
【问题讨论】:
-
CreateUser(ApplicationUser user, string password)有 2 个参数,但您只设置了一个参数。此外,您需要审查您的设计。它与实现问题的耦合过于紧密,无法进行测试。在前进的过程中,您会遇到更多的问题。 -
@Nkosi 好的,谢谢我将上面的行更改如下,然后错误消失
_identitityRepository.Setup(m => m.CreateUser(It.IsAny<ApplicationUser>(),"password")).Callback<ApplicationUser>(c => _users.Add(c));以使这个松散耦合我应该在哪里更改测试类或存储库? -
“松散耦合”是什么意思。该模拟参数不会使其耦合更紧密。它只负责方法签名。
-
@nozzleman Nkosi 说
it is too tightly coupled to implementation concerns to be test friendly在那里,我认为这会使耦合更松散,我应该在哪里更改以减少紧密耦合的情况,是测试类还是存储库? -
@kez 修复回调
.Callback<ApplicationUser,string>((u,p) => _users.Add(u));或.Callback((ApplicationUser u,string p) => _users.Add(u));
标签: c# unit-testing mocking asp.net-identity moq