看起来你肯定走在正确的轨道上,但让我试着解释一下我将如何进行测试。
这里实际的system under test (SUT) 是Authenticate 类。你没有说太多,所以我假设如下:
它使用ICustomerRepository 的实例根据用户名(电子邮件)和密码的组合来确定用户的存在。
当存储库返回 Customer 的实例时,给定用户名和密码组合,Login 方法返回 true。当仓库返回null时,Login方法返回false。
我将在下面使用这些假设,但如果它们不正确,我相信您将能够更改测试,以便它们对您的场景有意义。
测试一:当用户名/密码组合正确时,Login会返回true
public void LoginWillReturnTrueForAValidUsernamePasswordCombination()
{
string email = "test@test.com";
string password = "test";
//Dummy customer
var customer = new Customer();
//Create mock
var mockRepos = new Moq.Mock<ICustomerRepository>();
mockRepos.Setup(x => x.GetCustomerByPasswordUsername(
It.Is<string>(s => s == email),
It.Is<string>(s => s == password))
.Returns(customer);
var auth = new Authenticate(mockRepos.Object);
//Act
var result = auth.Login(email, password);
//Assert
Assert.IsTrue(result);
}
注意It.Is 的使用。基本上,模拟的设置方式是,当您的测试中定义的电子邮件和密码传递给 GetCustomerByPasswordUsername 方法时,它只会返回虚拟客户对象。
测试2:当用户名/密码组合不正确时,Login会返回false
public void LoginWillReturnFalseForAnInvalidUsernamePasswordCombination()
{
string email = "test@test.com";
string password = "test";
//Create mock
var mockRepos = new Moq.Mock<ICustomerRepository>();
mockRepos.Setup(x => x.GetCustomerByPasswordUsername(
It.Is<string>(s => s == email),
It.Is<string>(s => s == password))
.Returns<Customer>(null);
var auth = new Authenticate(mockRepos.Object);
//Act
var result = auth.Login(email, password);
//Assert
Assert.IsFalse(result);
}
虽然通过上述测试进行了隐式测试,但您可能希望更进一步,编写一个测试,以确保 Login 方法将正确的参数传递到存储库。这样的测试可能如下所示:
测试 3:登录将正确调用存储库
public void LoginWillInvokeGetCustomerByPasswordUsernameCorrectly()
{
string email = "test@test.com";
string password = "test";
//Create mock
var mockRepos = new Moq.Mock<ICustomerRepository>();
mockRepos.Setup(x => x.GetCustomerByPasswordUsername(
It.Is<string>(s => s == email),
It.Is<string>(s => s == password))
.Returns<Customer>(null)
.Verifiable();
var auth = new Authenticate(mockRepos.Object);
//Act (ignore result. We are only testing correct invocation)
auth.Login(email, password);
//Assert
mockRepos.Verify();
}
如果已经设置的方法没有被调用,模拟的Verify方法会抛出异常。
我希望这会有所帮助。如果您还有其他问题,请随时提问。