Guava @VisibleForTesting:帮我一个完整的例子 [英] Guava @VisibleForTesting : Help me with a complete example

查看:954
本文介绍了Guava @VisibleForTesting:帮我一个完整的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目的是对私有方法进行单元测试,并了解如何导入 @VisibleForTesting 并将其用于私有方法。我做了很多搜索,但无法看到演示此功能的完整示例。

My intent is to do unit test of private methods and I understand on how to import the @VisibleForTesting and use it for a private method. I have done a quite a bit of search but unable to see a complete example that demonstrates this feature.

例如:

class MyClass {
    @VisibleForTesting 
    private double[] getWorkArray(double[] values,int length) {
               :
               :
        return <some double array> 
    }
}

现在在JUnit中,我必须能够做到

Now in JUnit, I must be able to do

@Test
public void testProvateMethod() {
    MyClass object = new MyClass();
    assertNotNull(object.getWorkArray(...);
}

但是困难的部分是我无法理解/做以下
a)包含相关注释处理器的maven编译器插件片段
b)实际上能够测试私有方法。 (因为它抛出了与方法可见性相关的错误)

But the difficult part is I am unable to comprehend/do the following a) Snippet of maven compiler plugin for including the relevant annotation processor b) Actually be able to test a private method. (since it throws error related to visibility of method)

我在JUnit中编写测试时由于私有访问错误而无法执行操作。例如: mvn clean test

I am unable to do it in action while I write a test in JUnit (due to the private access error). For eg: mvn clean test

请提供完整的示例,了解获取JUnit测试的所有步骤私有方法完成。

Please provide a complete example to really all steps involved in getting the JUnit test of private methods done.

推荐答案

首先,我做建议测试私有方法,单元测试应该在大多数情况下测试公共方法。如果你必须测试私有方法,它通常表示设计不好。

Firstly, I do not recommend to test private methods, unit tests should test public methods in most cases. If you have to test private methods, it usually indicates a bad design.

关于 @VisibleForTesting ,它是用于Guava中的package-methods,而不是JUnit API的一部分。注释只是一个标记,表示可以测试方法,甚至不会在JVM中加载。因此,如果您需要测试非公共方法,使方法包范围对同一包中的单元测试类可见。

Regarding to @VisibleForTesting , it is used in package-methods in Guava, and not part of JUnit API. The annotation is just a tag to indicate the method can be tested, it even doesn't be loaded in JVM. So if you need to test non-public methods, make the methods package scope which is visible to unit test classes in same package.

最后,通过使用reflect可以访问私有方法,如果你真的需要测试它们。

Last, by using reflect can access private methods, if you really have to test them.

这篇关于Guava @VisibleForTesting:帮我一个完整的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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