【问题标题】:Mocking Objects Containing SubObjects With Rhino Mocks使用 Rhino Mocks 模拟包含子对象的对象
【发布时间】:2009-01-10 15:26:19
【问题描述】:

假设一个 IMouvement 对象包含一些子对象,例如 ITache、IStockPalette。

public interface IMouvement : IObjectBase<Guid>
{
        ITache Tache { get; set; }
        IStockPalette StockPalOrigine { get; set; }
}

如何使用 Rhino Mocks 模拟这个?

假设这个测试,这有什么问题?

[TestMethod]
public void Can_Validate_EmplacementTransitoireRule()
{
    var mocks = new MockRepository();
    var mouvement = mocks.StrictMock<IMouvement>();
    var manager = mocks.StrictMock<ValidationManager>();

    mouvement.Tache = mocks.StrictMock<ITache>();
    mouvement.StockPalOrigine = mocks.StrictMock<IStockPalette>();
    mouvement.ID = Guid.NewGuid();

    var rule = new EmplacementTransitoireRule(mouvement);
    manager.AddRule(rule);

    Expect.Call(manager.ValidateAll()).Return(true);

    mocks.ReplayAll();

    var all = manager.ValidateAll();

    mocks.VerifyAll();

    Assert.IsTrue(all);
}

这个测试总是失败..

【问题讨论】:

    标签: c# .net rhino-mocks


    【解决方案1】:

    通常我会对模拟对象设置期望,而不是仅仅分配它们的属性。

     Tache tache = mocks.StrictMock<Tache>();
     Expect.Call( mouvement.Tache ).Return( tache );
    

    此外,您可能希望对 RhinoMocks 使用 AAA (Arrange-Act-Assert) 语法——我相信 StrictMock 已被弃用。

     Mouvement mouvement = MockRepository.GenerateMock<Mouvement>();
     Tache tache = MockRepository.GenerateMock<Tache>();
    
     mouvement.Expect( m => m.Tache ).Return( tache );
     tache.Expect( t => t.Value ).Return( 100 );  // or whatever
    
     ... test code...
    
     tache.VerifyAllExpectations();
     mouvement.VerifyAllExpectations();
    

    【讨论】:

    • 好的,我刚试过,但现在我面临另一个问题。我需要排除受保护方法的结果,我可以使用 InternalsVisibleTo 程序集属性来让它与 rhino 模拟一起使用吗?
    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多