我有一个定义我的存储库的数据程序集。
然后我有一个定义我的服务的服务程序集,每个服务都有一个由 Ninject 注入到构造函数中的存储库。
当我对我的服务方法进行单元测试时,一切都很好:
[TestClass]
public class UserTests
{
IQueryable<User> users;
int userID;
public UserTests()
{
users = new List<User>()
{
new User { EmailAddress = "known@user.com", Password = "password", ID = 1}
}.AsQueryable();
}
[TestMethod]
public void Known_User_Can_Login()
{
// Arrange
var repository = new Mock<IUserRepository>();
var service = new UserService(repository.Object);
repository.Setup(r => r.GetAll())
.Returns(users);
// Act
bool loggedIn = service.UserLogin("known@user.com", "password", out userID);
// Assert
Assert.IsTrue(loggedIn);
Assert.AreEqual(1, userID);
}
[TestMethod]
public void Unknown_User_Cannot_Login()
{
// Arrange
var repository = new Mock<IUserRepository>();
var service = new UserService(repository.Object);
repository.Setup(r => r.GetAll())
.Returns(users);
// Act
bool loggedIn = service.UserLogin("unknown@user.com", "password", out userID);
//
Assert.IsFalse(loggedIn);
}
}
但是,我在测试我的控制器时遇到了问题(另一个级别)。
我的控制器依赖于服务,而服务依赖于存储库。我似乎无法让我的控制器测试正常工作。这是我到目前为止所拥有的:
[TestClass]
public class AccountTests
{
IQueryable<User> users;
public AccountTests()
{
users = new List<User>()
{
new User { CompanyId = 1, EmailAddress = "known@user.com", Password = "password"},
new User { CompanyId = 1, EmailAddress = "unknown@user.com", Password = "password"}
}.AsQueryable();
}
[TestMethod]
public void Known_User_Can_Login()
{
int userID = 0;
var repo = new Mock<IUserRepository>();
// Arrange
var service = new Mock<UserService>(repo.Object);
var controller = new AccountController(service.Object);
// Act
var result = controller.Login(new LoginModel { EmailAddress = "known@user.com", Password = "password" }) as RedirectToRouteResult;
// Assert
service.Verify(x => x.UserLogin("known@user.com", "password", out userID), Times.Once());
Assert.AreEqual("Index", result.RouteValues["Action"]);
}
}
我不断收到有关实例化 UserService 的错误(我正在尝试将 UserRepository 的实例传递给它,但它不起作用)。
我一定是在做一些愚蠢的事情,但是什么?