Java单元测试:替换正在测试的私有方法 [英] Java Unit Test: Replace a private method under test

查看:379
本文介绍了Java单元测试:替换正在测试的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行JUnit测试时,是否可以用任何方法替换私有方法中的逻辑?

Is there any way of replacing the logic within a private method when running a JUnit test?

背景知识:我们有一些私有方法,这些方法可与OSGi容器内的包进行交互.在单元测试中不可用,因此方法将失败.

A bit of background: we have some private methods which interact with bundles within an OSGi container. This is not available in the unit test therefore the methods will fail.

我们已经看过JMockIt,但是方法替换功能似乎要强迫您替换类中彼此调用的所有方法.

We have looked at JMockIt but the method replace functionality seems to want to force you to replace all the methods in the class which call one another.

实现将是这样的:

public final doSomething() {  
    firstThing();
    secondThing();
}
private firstThing() {  
    // normal code
}
private secondThing() {  
    // code which is unavailable in a unit test
}

并且单元测试将指定secondThing()的新实现:

And the unit test would specify the new implementation of secondThing():

// replace secondThing() in impl with this secondThing()

private secondThing() {  
    // dummy code
}

// run tests

推荐答案

您当然可以使用JMockit解决这种情况. 一种方法是定义一个模拟"类,例如:

You certainly can solve this situation with JMockit. One way would be to define a "mock-up" class, for example:

public class MyTest
{
    @Test
    public void testDoSomething()
    {
        new MockUp<ClassWhichDependsOnOtherBundles>()
        {
            @Mock
            void secondThing()
            {
               // do anything here
            }
        };

        new ClassWhichDependsOnOtherBundles().doSomething();
    }
}

仅模拟类中的secondThing()方法将由JMockit代替. 也可以使用JMockit Expectations API,并进行部分模拟.

Only the secondThing() method in the mocked class will be replaced by JMockit. The JMockit Expectations API could also be used, with partial mocking.

这篇关于Java单元测试:替换正在测试的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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