我可以模拟一个超类方法调用吗? [英] Can I mock a super class method call?

查看:158
本文介绍了我可以模拟一个超类方法调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,您希望测试一个类方法,并且希望在调用超类方法时进行预期。我没有找到一种方法来使用easymock或jmock在java中做这个期望(我认为这是不可能的)。

Sometimes, you want to test a class method and you want to do an expectation on a call of a super class method. I did not found a way to do this expectation in java using easymock or jmock (and I think it is not possible).

有一个(相对)干净的解决方案,使用超类方法逻辑创建委托,然后设置它的期望,但我不知道为什么以及何时使用该解决方案?任何想法/示例?

There is a (relative) clean solution, to create a delegate with the super class method logic and then set expectations on it, but I don't know why and when use that solution ¿any ideas/examples?

谢谢

推荐答案

嗯,如果你愿意,你可以。我不知道您是否熟悉 JMockit ,请查看它。当前版本是0.999.17同时,我们来看看它......

Well, you can if you want to. I don't know if you are familiar with JMockit, go check it out. The current version is 0.999.17 In the mean time, let's take a look at it...

假设以下类层次结构:

public class Bar {
    public void bar() {
        System.out.println("Bar#bar()");
    }
}

public class Foo extends Bar {
    public void bar() {
        super.bar();
        System.out.println("Foo#bar()");
    }
}

然后,在 FooTest.java 您可以验证您实际上是从 Foo Bar c>。

Then, using JMockit in your FooTest.java you can validate that you're actually making a call to Bar from Foo.

@MockClass(realClass = Bar.class)
public static class MockBar {
    private boolean barCalled = false;

    @Mock
    public void bar() {
        this.barCalled = true;
        System.out.println("mocked bar");
    }
}

@Test
public void barShouldCallSuperBar() {
    MockBar mockBar = new MockBar();
    Mockit.setUpMock(Bar.class, mockBar);

    Foo foo = new Foo();
    foo.bar();

    Assert.assertTrue(mockBar.barCalled);

    Mockit.tearDownMocks();
}

这篇关于我可以模拟一个超类方法调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆