2012-07-16 71 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 
     }