2009-07-03 7 views
0

は、私はユニットテストしたいメソッドCreateAccount(...)を持っています。基本的に、Account Entityを作成してDBに保存し、新しく作成したAccountを返します。私はリポジトリを嘲笑して、Insert(...)呼び出しを期待しています。しかし、InsertメソッドはAccountオブジェクトを必要とします。が正しくユニットテストサービス/リポジトリの相互作用

このテストはパスするが、CreateAccountがアカウントを作成するので、それだけで、正しいいないようだ、と私はMock'ed期待コール(2つの別々のアカウントインスタンス)のアカウントを作成しています。この方法をテストする正しい方法は何でしょうか?それとも、この方法を使ってアカウントを作成しているのですか?

[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

+1

私は2つの別々のインスタンスが作成されているのでnewAccとアカウントが同じになる方法を見てはいけません。またはAreSame()は型を比較す​​るだけですか? – mxmissile

+1

正しい。 AreSameはオブジェクトのインスタンスを比較して、元の私の答えが正しくないようにします。私は以来、いくつかの修正を追加しました(上に) – jpoh

関連する問題