[英]Test Lombok's @UtilityClass auto-generated code
I have a class that's annotated with @UtilityClass
like this我有一个像这样用@UtilityClass
注释的类
@UtilityClass
public class myUtilClass {
...
}
JaCoCo doesn't give me full coverage for this class because of the auto-generated code created by the annotation @UtilityClass
.由于注释@UtilityClass
创建的自动生成的代码,JaCoCo 没有完全覆盖这个类。 Ideally, I do not want to change any config files to ignore auto-gen code.理想情况下,我不想更改任何配置文件以忽略自动生成代码。 How can this code be tested?如何测试这段代码?
The only "coverable" code that is generated by @UtilityClass
is in the constructor: @UtilityClass
生成的唯一“可覆盖”代码在构造函数中:
private MyUtilClass() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
As this is a private
constructor that never should be called, you cannot test it regularly.由于这是一个永远不应调用的private
构造函数,因此您无法定期对其进行测试。
If you really want to call it, you can do it with some ugly reflective code:如果你真的想调用它,你可以用一些丑陋的反射代码来实现:
Constructor<MyUtilClass> constructor;
constructor = MyUtilClass.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();
But you should not do this just for the sake of coverage.但是您不应该仅仅为了报道而这样做。 Having a high coverage is generally a good idea, but not if you have to sacrifice good testing standards.拥有高覆盖率通常是一个好主意,但如果您必须牺牲良好的测试标准,则不是。
I suggest you advice JaCoCo to ignore Lombok's code by adding this line to your lombok.config
file:我建议您建议 JaCoCo 通过将这一行添加到您的lombok.config
文件来忽略 Lombok 的代码:
lombok.addLombokGeneratedAnnotation = true
You don't have to configure this for your whole project.您不必为整个项目配置它。 If you put this file only into the package of MyUtilClass
, JaCoCo will only ignore generated code in this package.如果仅将此文件放入MyUtilClass
的包中,JaCoCo 将仅忽略此包中生成的代码。
Just write this unit test to ensure your class cannot be instantiated because of @UtilityClass annotation.只需编写此单元测试以确保您的类无法因为 @UtilityClass 注释而被实例化。 Then, coverage will be OK.然后,覆盖就可以了。
@Test
void test_cannot_instantiate() {
assertThrows(InvocationTargetException.class, () -> {
var constructor = YOUR_CLASS_NAME.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
constructor.newInstance();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.