任何人都可以解释为什么在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>()));
如何确保仅调用替代方法?
答案 0 :(得分: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 {}
}