简体   繁体   English

使用JMockit在抽象类中模拟非公共静态方法?

[英]Mocking non-public static methods in abstract classes with JMockit?

I have the following class: 我有以下课程:

public abstract class AbstractParent {
    static String method() {
        return "OriginalOutput";
    }
}

I want to mock this method. 我想嘲笑这个方法。 I decide to use JMockit . 我决定使用JMockit So I create a mock class: 所以我创建了一个模拟类:

public class MockParent {
    static String method() {
        return "MOCK";
    }
}

And my test code looks like this: 我的测试代码如下所示:

public class RealParentTest {

    @Before
    public void setUp() throws Exception {
        Mockit.redefineMethods( AbstractParent.class, MockParent.class );
    }


    @Test
    public void testMethod() {
        assertEquals(MockParent.method(),AbstractParent.method());
    }

}

Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". 不幸的是,这个测试表明AbstractParent返回“OriginalOutput”而不是“MOCK”。 Any ideas why? 有什么想法吗? Am I doing something wrong? 难道我做错了什么? I've tried declaring my mock class as abstract as well, to no avail. 我已经尝试将我的模拟类声明为抽象,但无济于事。

Edit Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope. 编辑注意,使方法公开会导致测试运行没有问题...这很奇怪,因为使用JMockit,您应该能够模拟任何范围的方法。

Answer Only the mock method needs to be public, you can leave the original method as is. 回答只有mock方法需要公开,你可以保留原来的方法。

Found the solution: you simply need to make the mock's method public (the original method can stay in its original visibility). 找到解决方案:你只需要将mock的方法设为public(原始方法可以保持其原始可见性)。

I don't know why this works while the original way doesn't (someone who does is more than welcome to chime in), but all you need to do is simply change the mock class in the example above to: 我不知道为什么这种方法有效,而原始方式却没有(有人欢迎加入),但你需要做的只是将上面例子中的mock类更改为:

public class MockParent {
    public static String method() {
        return "MOCK";
    }
}

Apparently the new way to do this is to use MockUp<T> 显然,执行此操作的新方法是使用MockUp<T>

new MockUp<AbstractParent>(){
    @Mock String method() {
        return "MOCK";
    }
};

assertEquals("MOCK" AbstractParent.method());

Another alternative is apparently to continue with something like MockParent with a @MockClass annonation. 另一种选择显然是继续使用MockParent@MockClass annonation这样的东西。 Haven't done this myself as the another inline version does the job. 自己没有这样做,因为另一个内联版本完成了这项工作。

I've implemented this in an example project on github . 在github上的一个示例项目中实现了这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM