0

谁能解释一下为什么在 RhinoMocks 中这段代码仍然执行 native 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>()));

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

4

1 回答 1

0

我尝试了您的代码段,它对我返回预期的空集合很有效。我能想象你为什么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 {}
}
于 2012-06-21T15:43:04.030 回答