【问题标题】:How to replace the execution of a method with RhinoMocks如何用 RhinoMocks 替换方法的执行
【发布时间】:2012-06-21 15:16:22
【问题描述】:

谁能解释一下为什么在 RhinoMocks 中这段代码仍然会执行原生的SomeVirtualMethod

var repository = MockRepository.GenerateStub<MyRepository>(null, null);
repository.Stub(x => x.SomeVirtualMethod()).Return(new List<SomeObject>());

当第二行运行时,原来的SomeVirtualMethod 运行并崩溃,因为它脱离了上下文。我也试过:

var repository = MockRepository.GenerateStub<MyRepository>(null, null);
repository.Stub(x => x.SomeVirtualMethod()).Do(new Func<List<SomeObject>>(() => new List<SomeObject>()));

如何确保只调用替代方法?

【问题讨论】:

    标签: .net c#-4.0 mocking rhino-mocks


    【解决方案1】:

    我尝试了您的 sn-p,它对我返回预期的空集合效果很好。我能想象你的SomeVirtualMethod 仍然被执行的唯一原因,因为它实际上不是虚拟的!请再次检查。

    这是我试过的代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Rhino.Mocks;
    
    namespace TestProject1
    {
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void TestMethod1()
            {
                var stub = MockRepository.GenerateStub<MyRepository>(null,null);
                stub.Stub(x => x.SomeVirtualMethod()).Return(new List<SomeObject>());
                Assert.AreEqual(0, stub.SomeVirtualMethod().Count());
            }
        }
    
        public class MyRepository {
    
            public MyRepository(object a1, object a2) { }
            public virtual IEnumerable<SomeObject> SomeVirtualMethod()
            {
                throw new NotImplementedException();
            }
        }
    
        public class SomeObject {}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多