如何使用Rhino Mock 模拟未实现的方法?

发布于 2025-01-04 21:52:29 字数 572 浏览 4 评论 0原文

我有这个简化的实现和单元测试如下:

public class Parent
{
    public virtual int GetSomeValue()
    {
        throw new NotImplementedException();
    }
}

public class Child
{
    public Parent MyParent { get; set; }

    public virtual Parent GetParent()
    {
        return MyParent;
    }

    public virtual int GetParentsValue()
    {
        var parent = GetParent();

        return parent.GetSomeValue();
    }
}

How can I test the GetParentsValue() method with Rhino Mock without Implement the Parent's GetSomeValue() method?

谢谢!

I have this simplified implementation and the unit test below:

public class Parent
{
    public virtual int GetSomeValue()
    {
        throw new NotImplementedException();
    }
}

public class Child
{
    public Parent MyParent { get; set; }

    public virtual Parent GetParent()
    {
        return MyParent;
    }

    public virtual int GetParentsValue()
    {
        var parent = GetParent();

        return parent.GetSomeValue();
    }
}

How can I test the GetParentsValue() method with Rhino Mock without implement the parent's GetSomeValue() method?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木落 2025-01-11 21:52:29

你可以这样做:

Child target = new Child();

Parent mockParent = MockRepository.GenerateStub<Parent>();
mockParent.Stub(x => x.GetSomeValue()).Return(1);

target.MyParent = mockParent;

int value = target.GetParentsValue();

Assert.AreEqual(value, 1);

You can do this:

Child target = new Child();

Parent mockParent = MockRepository.GenerateStub<Parent>();
mockParent.Stub(x => x.GetSomeValue()).Return(1);

target.MyParent = mockParent;

int value = target.GetParentsValue();

Assert.AreEqual(value, 1);
冬天旳寂寞 2025-01-11 21:52:29

您可以使用以下代码:

Child child = MockRepository.GenerateStrictMock<Child>();
child.Stub(c => c.GetParentsValue()).Return(1);

Assert.AreEqual(1, child.GetParentsValue());

如果您想测试 GetParentsValue() 方法的一些内部原理,您应该使用以下代码模拟 Parent.GetSomeValue()

Parent mockParent = MockRepository.GenerateStub<Parent>();
mockParent.Stub(x => x.GetSomeValue()).Return(1);

target.MyParent = mockParent;

You can use this code:

Child child = MockRepository.GenerateStrictMock<Child>();
child.Stub(c => c.GetParentsValue()).Return(1);

Assert.AreEqual(1, child.GetParentsValue());

If you want to test some internals of the GetParentsValue() method you should mock Parent.GetSomeValue() with:

Parent mockParent = MockRepository.GenerateStub<Parent>();
mockParent.Stub(x => x.GetSomeValue()).Return(1);

target.MyParent = mockParent;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文