2009-07-03 46 views
0

我有一个方法CreateAccount(...),我想单元测试。基本上它创建一个帐户实体并将其保存到数据库,然后返回新创建的帐户。我在嘲笑仓库并期待Insert(...)调用。但是Insert方法需要一个Account对象。正确单元测试服务/库交互

此测试通过,但它似乎不正确,因为CreateAccount创建一个帐户,并且我为Mock'ed期望的呼叫(两个单独的帐户实例)创建一个帐户。测试这种方法的正确方法是什么?或者是我使用这种方法创建帐户不正确?

[Fact] 
    public void can_create_account() 
    { 
     const string email = "[email protected]"; 
     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; 
    } 

回答

1
[Test] 
public void can_create_account() 
{ 
    const string email = "[email protected]"; 
    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调用,并使用上面的属性比较(以确保对象的正确实例用作此调用的参数)。

+1

对不起,我应该发布我正在测试的实际方法,杜。我更新了OP。 – mxmissile 2009-07-03 17:30:02