0

以下のようなリポジトリがあります。

internal class Repository<T> : IRepository<T> where T : class
{
    public virtual ITable GetTable()
    {
        return _context.GetTable<T>();
    }

    public virtual void InsertOnSubmit(T entity)
    {
        GetTable().InsertOnSubmit(entity);
    }

    public virtual void SubmitChanges()
    {
        _context.SubmitChanges();
    }
}

System under Test クラスは次のようになります。

public class CustomerHelper
{
    private readonly IRepository<Customer> _customerRepository;
    CustomerHelper(IRepository<Customer> customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public void CreateCustomer(int createdBy, int customerId)
    {
        var customerToUpdate = _customerRepository.Get.Single(c => c.Id == customerId)

        customerToUpdate.CreatedBy =createdBy;
        customerToUpdate.CreateDate = DateTime.Now;

        _customerRepository.InsertOnSubmit(customerToUpdate);
        _customerRepository.SubmitChanges();
    }
}

RhinoMocks を使用して、以下のような CreateCustomer メソッドに対する私のテスト メソッド。

[TestMethod]
public void CreateCustomer()
{
    // Arrange
    Customer customer = new Customer
    {
        Id = 1
    };
    IRepository<Customer> repository =  MockRepository.GenerateMock<IRepository<Customer>>();
    var customerList = new List<Customer> { customer }.AsQueryable();

    repository.Stub(n => n.Get).Return(nonLaborclassificationList);

    CustomerHelper helper = new Customer(repository);
    helper.CreateCustomer(1, customer.Id);

    // Now here I would liek to test whether CreatedBy, CreateDate fields on    cutomer are updated correctly. I've tried the below

    Customer customerToUpdate;

    repository.Stub(c => c.InsertOnSubmit(customer)).WhenCalled(c => { customerToUpdate = n.Arguments[0]; } );
    Assert.AreEqual(1, customerToUpdate.CreatedBy);
}

上記のコードは機能しません。methodからインスタンスInsertOnSubmit()を取得しようとして、 method をスタブしている場所。が適切に設定されていることを確認するためにアサートを作成するにはどうすればよいですか?customerToUpdateCreateCustomer()CreatedByCreateDate

4

2 に答える 2

0

一般的な戦略は次のとおりです。

  1. リポジトリをスタブして、更新する特定の顧客を返します
  2. 必要なアクションを実行します。helper.CreateCustomer()
  3. 最初にスタブ化したオブジェクトに正しい値が設定されているかどうかを確認します

この場合、リポジトリにスタブ化された、作成した最初の Customer オブジェクトを確認するだけでよいでしょう。テストしている実際のコードは同じオブジェクト (同じ参照) を使用しているため、からオブジェクトを取得するコードの最後のビットは本当に必要ありませんInsertOnSubmit()。ただし、それでもやりたい場合は、次を使用AssertWasCalledして支援できます。

repository.AssertWasCalled(
  x => x.InsertOnSubmit(Arg<Customer>.Matches(c => c.CreateBy))

デバッグにGetArgumentsForCallsMadeOnは、デバッガーでステップ実行できる場合に役立つ方法もあります。

于 2013-02-21T23:05:42.863 に答える
0

コードには 2 つの問題があります。

  1. ジェフ・ブリッジマンがコメントで述べているように、nonLaborclassificationList定義されていません。customerList代わりに返されるべきだと思います。

  2. InsertOnSubmit()forrepositoryは、テスト アクションhelper.CreateCustomer(1, customer.Id)の実行後にスタブ化されます。したがって、このスタブは機能しません。ArrangeAct
    の前 に配置されるため、スタブはテスト アクションの前に設定する必要があります。

CreatedDateそしてもちろん、が正しく設定されているかどうかをアサートしたい場合はAssert、そのために特別に書く必要があります :) 。

于 2013-03-02T10:20:34.853 に答える