我有一个方法CreateAccount(...),我想进行单元测试。基本上它创建一个帐户实体并将其保存到数据库,然后返回新创建的帐户。我正在嘲笑存储库并期待一个Insert(...)调用。但Insert方法需要一个Account对象。
此测试通过,但它似乎不正确,因为CreateAccount创建了一个帐户,我正在为Mock'ed预期调用创建一个帐户(两个单独的帐户实例)。测试此方法的正确方法是什么?或者我使用此方法创建帐户不正确?
[Fact]
public void can_create_account()
{
const string email = "test@asdf.com";
const string password = "password";
var accounts = MockRepository.GenerateMock<IAccountRepository>();
accounts.Expect(x => x.Insert(new Account()));
var service = new AccountService(accounts);
var account = service.CreateAccount(email, password, string.Empty, string.Empty, string.Empty);
accounts.VerifyAllExpectations();
Assert.Equal(account.EmailAddress, email);
}
这是CreateAccount方法:
public Account CreateAccount(string email, string password, string firstname, string lastname, string phone)
{
var account = new Account
{
EmailAddress = email,
Password = password,
FirstName = firstname,
LastName = lastname,
Phone = phone
};
accounts.Insert(account);
return account;
}
答案 0 :(得分:1)
[Test]
public void can_create_account()
{
const string email = "test@asdf.com";
const string password = "password";
Account newAcc = new Account();
var accounts = MockRepository.GenerateMock<IAccountRepository>();
var service = new AccountService(accounts);
var account = service.CreateAccount(email, password, string.Empty,
string.Empty, string.Empty);
accounts.AssertWasCalled(x => x.Insert(Arg<Account>
.Matches(y => y.EmailAddess == email
&& y.Password == password)));
Assert.AreEqual(email, account.EmailAddress);
Assert.AreEqual(password, account.Password);
}
所以你在这里测试的本质上是一个工厂方法(即它创建一个对象的新实例并返回它)。我知道测试这些方法的唯一方法是检查我们返回的对象是否具有我们期望的属性(上面的最后两个Assert.Equal调用正在执行此操作)。您还可以在方法中对存储库进行额外调用;因此我们需要使用上面的属性比较进行额外的AssertWasCalled调用(以确保将对象的正确实例用作此调用的参数)。