【发布时间】:2021-08-16 19:59:57
【问题描述】:
我在我的项目中使用 mapstruct,最近使用 ptest 添加了一些“突变分析”。
我遇到的问题是在某些生成的代码上创建了一个突变体,我无法修复我的测试来杀死它,因为这是关于 mapstruct 生成的空检查,这是无法访问的。
即,如果我有以下映射器:
@Mapper
public abstract class MyMapper {
@Mapping(source= "someInnerObject.field", target="someField")
public abstract Bar toBar(Foo foo);
}
Mapstruck 会生成类似这样的东西:
public class MyMapperImpl extends MyMapper {
@Override
public Bar toBar(Foo foo) {
if(foo == null) {
return null; // reacheable code, all is fine here.
}
Bar bar = new Bar();
bar.setSomeField(fooSomeField(foo))
return bar;
}
private String fooSomeField(Foo foo) {
if (foo == null) {
return null; // Unreacheable code, already tested in public method.
}
SomeInnerObject innerObject = foo.getSomeInnerObject()
if(innerObject == null) {
return null; // reacheable code, no problem here
}
String field = o.getField();
if(field == null) {
return null; // reacheable, no problem here.
}
return field;
}
}
正如我们所见,mapstruct 会生成一个无法访问的空检查,因此无法在测试中覆盖这些行。突变分析器尝试在无法到达的行上返回“”而不是 null,因此,我的测试从未检测到突变体。这导致无法获得 100% 的代码覆盖率和 100% 的变异覆盖率。
我认为从覆盖范围或突变分析中排除这个生成的代码不是一个好的选择,因为生成的代码反映了在映射器中编码为注释的行为:所以我们希望确保这些行为是在测试中正确覆盖。
这里有人有同样的问题,或者有什么建议吗?
我尝试了许多不同的映射器配置来摆脱无法访问的行但没有成功(除非我只是禁用所有空检查,这会改变我的应用程序逻辑)。
【问题讨论】:
标签: code-coverage mapstruct mutation-testing