我对以下控制器操作方法进行了简单的测试
管理控制器
namespace TestingDemo {
public class AdminController : Controller {
private IUserRepository repository;
public AdminController(IUserRepository repo) {
repository = repo;
}
public ActionResult ChangeLoginName(string oldName, string newName) {
User user = repository.FetchByLoginName(oldName);
user.LoginName = newName;
repository.SubmitChanges();
// render some view to show the result
return View();
}
}
}
我的测试就是这个
namespace TestingDemo.Tests {
[TestClass]
public class AdminControllerTests {
[TestMethod]
public void CanChangeLoginName() {
// Arrange (set up a scenario)
User user = new User() { LoginName = "Bob" };
FakeRepository repositoryParam = new FakeRepository();
repositoryParam.Add(user);
AdminController target = new AdminController(repositoryParam);
string oldLoginParam = user.LoginName;
string newLoginParam = "Joe";
// Act (attempt the operation)
target.ChangeLoginName(oldLoginParam, newLoginParam);
// Assert (verify the result)
Assert.AreEqual(newLoginParam, user.LoginName);
Assert.IsTrue(repositoryParam.DidSubmitChanges);
}
}
class FakeRepository : IUserRepository {
public List<User> Users = new List<User>();
public bool DidSubmitChanges = false;
public void Add(User user) {
Users.Add(user);
}
public User FetchByLoginName(string loginName) {
return Users.First(m => m.LoginName == loginName);
}
public void SubmitChanges() {
DidSubmitChanges = true;
}
}
}
我的问题是user.LoginName是如何变更的?用户发生的唯一变化是在action方法中,这是一个本地用户变量。测试中的用户变量如何更新?
答案 0 :(得分:0)
控制器测试首先使用List<User> Users
方法将用户添加到虚拟存储库中的Users.Add
。
添加到的存储库将传递到测试中控制器的构造函数中:
AdminController target = new AdminController(repositoryParam);