CodeGo.net>如何用Rhino模拟存根SingleOrDefault
作者:互联网
如果我在这里找到正确的方法,我很难理解.我想测试一个存储库.该存储库取决于DbContext.我希望能够验证存储库未在IDbSet类型的属性(它是DbContext的成员)上调用函数Add.
我尝试了两种方法.验证行为,并验证状态.似乎可以用行为进行验证是正确的,因为谁知道伪造对象中的存根状态在做什么.
public void VerifyBehaviour()
{
// Arrange
var stubEntities = MockRepository.GenerateStub<IWsStatContext>();
var stubManufcturers = MockRepository.GenerateStub<IDbSet<Manufacturer>>();
var manufacturer = new Manufacturer() { Name = "Dummy" };
var manufacturers = new List<Manufacturer>();
manufacturers.Add(manufacturer);
stubManufcturers.Stub(x => x.Local).Return(new System.Collections.ObjectModel.ObservableCollection<Manufacturer>(manufacturers));
stubManufcturers.Stub(x => x.SingleOrDefault(m => m.Name == "Dummy")).Return(manufacturer);
stubEntities.Manufacturers = stubManufcturers;
// Act
var sut = new EquiptmentRepository(stubEntities);
sut.AddManufacturer(manufacturer);
// Assert
stubManufcturers.AssertWasNotCalled(x => x.Add(manufacturer));
}
public void VerifyState()
{
// Arrange
var stubEntities = MockRepository.GenerateStub<IWsStatContext>();
var stubManufacturers = new InMemoryDbSet<Manufacturer>();
var manufacturer = new Manufacturer() { Name = "Dummy" };
stubManufacturers.Add(manufacturer);
stubEntities.Manufacturers = stubManufacturers;
// Act
var sut = new EquiptmentRepository(stubEntities);
sut.AddManufacturer(manufacturer);
// Assert
Assert.AreEqual(stubManufacturers.Count(), 1);
}
验证行为方法失败,并在SingleOrDefault的存根周围显示NullReferenceExceptions.因此,我发现最好说的是验证状态并使用伪造的DbSet的帖子.但是,检查虚假对象的状态感觉不对.如果Add函数的实现与真正函数的实现不同(该函数最初是我的并且即使我的存储库已损坏,我的测试也通过了),该怎么办?
有谁知道如何对SingleOrDefault存根,以便我可以检查Add是否被调用?我无法检查“ Add”是否在非犀牛存根上调用.
谢谢
解决方法:
如jimmy_keen’s answer中所述:
SingleOrDefault
is an extension method defined onIEnumerable<T>
(whichIDbSet<T>
implements). Being extension method means it is a static method. RhinoMocks (or any other free tool) cannot mock/stub static methods.
而不是尝试“扩展”扩展方法,而尝试扩展该扩展方法所基于的基础接口:IEnumerable< T>
stubManufcturers.Stub( x => x.GetEnumerator() ).Return( new List<Manufacturer> { manufacturer }.GetEnumerator() );
通过在调用SingleOrDefault时对GetEnumerator()的行为进行存根,它将按预期对伪枚举执行,并且测试将能够评估该行为.
标签:unit-testing,entity-framework-4,c,rhino-mocks 来源: https://codeday.me/bug/20191101/1982957.html