我执行的JUnit测试失败:
$ mvn -U clean test
但是,当我使用install
执行构建时,它会成功:
$ mvn -U clean install
问题:以前是否有人遇到过这种情况?如果是,可能是什么原因引起的?
我正在测试的代码将实体层次结构转换为相似的DTO层次结构。有一个模拟的Function
,它针对给定的List
返回由4个Child
组成的String
个实体,并注入到测试中的类中。
从List
获得ChildDTO
个实例中的ParentDTO
个实例时,将发生故障。 应该包含4个ChildDTO
实例,但为空。
使用Maven 3.5.0
public class Child {
private String name;
}
public class Parent {
private List<Child> children;
public List<Child> getChildren() {
return children;
}
}
在此讨论中,假定DTO类与这些实体紧密匹配。
public class ThingToTest {
@Autowired
private Function<String, List<Child>> fetchChildren;
public ParentDTO doSomething(Parent parent) {
List<Child> childList = fetchChildren.apply("John");
// Convert to DTO representations
return parentDto;
}
}
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@Mock
private Function<String, List<Child>> fetchChildren;
@InjectMocks
private ThingToTest thingToTest;
@Test
public void testDoSomething() {
// Manually create a List of Child instances.
List<Child> mockListOfChildren = generateChildren();
// Mock the response to the Function's apply() method.
Mockito.when(fetchChildren.apply("some-string")).thenReturn(mockListOfChildren);
// Execute the code to be tested.
ParentDTO parentDto = thingToTest.doSomething();
assertNotNull(parentDto);
List<ChildDTO> childList = parentDto.getChildren();
assertNotNull(childList);
assertEquals(4, childList.size()); // <- Fails here: "expected:<4> but was:<0>"
}