2012-07-16 74 views
2

我與FindBy方法採取在謂語以下回購接口如何嘲笑說TAKS謂語用犀牛製品的方法

public interface IRepo<T> where T : class 
{ 
    IList<T> GetAll(); 
    IList<T> FindBy(Expression<Func<T, bool>> predicate); 
    void Add(T entity); 
    void Edit(T entity); 
} 

我想測試我的控制器是否確實調用此方法。這裏是我的控制器代碼

// GET:/Assets/EditAssets 
    public PartialViewResult EditAsset(Guid id) 
    { 
     var asset = _assetRepo.FindBy(ass => ass.Id == id).FirstOrDefault(); 

     if (asset == null) 
     { 
      return PartialView("NotFound"); 
     } 

     SetUpViewDataForComboBoxes(asset.AttachedDeviceId); 
     return PartialView("EditAsset", asset); 
    } 

,這裏是我的測試方法

[TestMethod] 
    public void editAsset_EmptyRepo_CheckRepoCalled() 
    { 
     //Arrange 
     var id = Guid.NewGuid(); 

     var stubAssetRepo = MockRepository.GenerateStub<IRepo<Asset>>(); 
     stubAssetRepo.Stub(x => x.FindBy(ass => ass.Id == id)).Return(new List<Asset> {new Asset()}); 

     var adminAssetsControler = new AdminAssetsController(stubAssetRepo, MockRepository.GenerateStub<IRepo<AssetModel>>(), MockRepository.GenerateStub<IRepo<AssetSize>>(), MockRepository.GenerateStub<IRepo<AssetType>>(), MockRepository.GenerateStub<IRepo<Dept>>(), MockRepository.GenerateStub<IRepo<Device>>()); 

     //Act 
     var result = adminAssetsControler.EditAsset(id); 

     //Assert 
     stubAssetRepo.AssertWasCalled(rep => rep.FindBy(ass => ass.Id == id)); 
    } 

但我得到一個argumentNullException。我之前在做過謂詞的測試之前就已經做過這種測試了,並且它工作正常。那麼這個是怎麼回事?

有沒有一種很好的方法來設置這種測試?

回答

1

首先,避免空引用異常,你可以只使用IgnoreArguments()

stubAssetRepo.Stub(x => x.FindBy(null)).Return(new List<Asset> {new Asset()}).IgnoreArguments() 

的事情是,你可能要驗證的拉姆達傳遞給FindBy方法,它的參數。您可以使用WhenCalled()方法來完成此操作,您可以按照here的說明將lambda轉發到另一種方法。
完整的代碼看起來像這樣:

  ... 
       stubAssetRepo.Stub(x => x.FindBy(null)).Return(new List<Asset> {new Asset()}). 
    IgnoreArguments().WhenCalled(invocation => FindByVerification((Expression<Func<Asset, bool>>)invocation.Arguments[0])); 
     .... 

      //Act 
      var result = adminAssetsControler.EditAsset(id); 

      //Assert 
      stubAssetRepo.VerifyAllExpectations(); 
     } 

     public void FindByVerification(Expression<Func<Asset, bool>> predicate) 
     { 
      // Do your FindBy verification here, by looking into 
      // the predicate arguments or even structure 
     }