【问题标题】:How to mock inherited methods如何模拟继承的方法
【发布时间】:2011-10-30 19:44:19
【问题描述】:

我试图模拟一个从通用父类继承的方法。知道我的代码是这样的。

public interface IBaseRepository<T>
{
    IEnumerable<T> FindMany(Func<T, bool> condition);
}

public interface IPersonRepository : IBaseRepository<person>
{
    //Here I got some specifics methods for person repository
}

我的测试代码是这样的;

    private IPersonRepository mockPersonRepository { get; set; }

    [TestMethod]
    public void TestMehtod()
    {
        LogonModel model = CreateLogonModel("test@test.com", "test", "Index");
        person p = new person() { Email = model.Email, password = model.Password, PersonId = 1 };

        mockPersonRepository.Stub(x => x.FindMany(y => y.Email == model.Email && y.password == model.Password)).Return(new List<person> {p});
        mockPersonRepository.Replay();

        var actual = instanceToTest.LogOnPosted(model) as PartialViewResult;

        Assert.AreEqual("_Login", actual.ViewName);
    }

当我在 vs 2010 中使用调试工具时,我可以看到我的 Stub,不起作用,返回的人始终为空。我已将 FindMany 方法声明为虚拟方法。

有人知道如何存根该方法吗?我正在使用 RhinoMocks。

【问题讨论】:

    标签: c# model-view-controller unit-testing rhino-mocks


    【解决方案1】:

    问题是您正在比较 lambda - 但您真的有兴趣让 person 实例传递到 lambda 基于满足谓词条件匹配您的 person 对象 - 您可以使用Matches() 来实现这一点,只需在p 上执行谓词——如果它等于true,那么你有一个匹配项,应该返回存根列表:

    mockPersonRepository.Stub(x => x.FindMany(Arg<Func<person, bool>>.Matches( y => y(p))))
                        .Return(new List<person> { p });
    

    【讨论】:

    • 感谢您的帮助,它真的帮助了我!现在我想测试我是否真的使用了我传递给方法 LogonPosted 的模型。我怎样才能做到这一点?我一直在尝试这样做:mockPersonRepository.Expect(x => x.FindMany(Arg>.Matches(y => y(p)))).Return();但是,如果我这样设置我的测试,它总是会变绿。我如何期望我真的用模型中的数据调用 personRepository。
    猜你喜欢
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2015-09-09
    • 2011-09-18
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多