【发布时间】:2020-09-25 20:18:25
【问题描述】:
我还没有看到以解决我的问题的方式回答这个特定问题。
我有一个由存储库和 Orika MapperFacade 构建的服务类。在测试中,我正在安排存储库调用返回的实体列表。我的 doReturn(testList).when(testRepository).findAllBy... 似乎正在工作。我的实际结果列表包含我在模拟列表中指定的相同数量的元素 (.size()),但是这些值都是空的。我对 Spring Boot 还很陌生,对 Mockito 也很陌生。我目前正在使用一个 bean,它返回一个使用 MapperFactory 创建的 MapperFacade,并定义了几个类映射。现在我在测试中为我的 MapperFacade 使用@Spy,并且可以严格基于断言列表的大小是相同的。我知道我可能需要@Mock 行为或 MapperFacade,尽管它被用于迭代服务类中的列表。不确定如何在测试中实现它。我可以构建另一个 DTO 列表,该列表通常会从遍历实体的循环中返回,但我是 Mockito 语法的新手,不知道如何运行该返回。
我在尝试从列表元素中记录或断言 .getAnyValue 时收到 NullPointerException,但是当我在排列的列表中添加或删除元素时,列表的大小会发生变化。
任何信息表示赞赏。
服务类
public class FightService {
private FightRepository repository;
private MapperFacade mapper;
@Autowired
public FightService(FightRepository r, MapperFacade m) {
this.repository = r;
this.mapper = m;
}
public List<FightDTO> getFightsByWinRound(int winRound){
List<FightEntity> entities = repository.findAllByWinRound(winRound);
List<FightDTO> returnVal = new ArrayList<>();
for(FightEntity e: entities){
FightDTO dto = mapper.map(e, FightDTO.class);
returnVal.add(dto);
}
return returnVal;
}
}
服务测试
@Slf4j
@RunWith(MockitoJUnitRunner.class)
public class FightServiceTest{
@Spy
private MapperFacade mapperFacade;
@Mock
private FightRepository testRepository;
@InjectMocks
private FightService systemUnderTest;
@Test
public void testGetFightsByWinRound_ScenarioA() throws Exception{
//Arrange
List<FightEntity> testList = new ArrayList<>();
FightEntity fightA = new FightEntity();
fightA.setFighter1("A");
fightA.setWinRound(15);
testList.add(fightA);
FightEntity fightB = new FightEntity();
fightB.setFighter1("B");
fightB.setWinRound(15);
testList.add(fightB);
FightEntity fightC = new FightEntity();
fightC.setFighter1("C");
fightC.setWinRound(15);
testList.add(fightC);
doReturn(testList).when(testRepository).findAllByWinRound(15);
//Act
List<FightDTO> actual = systemUnderTest.getFightsByWinRound(15);
//Assert
Assert.assertThat(actual.size(), is(3));
// I would be adding Assert.assertThat(actual.get(0).getFighter1(), is("A")) , but this is where the NPE arises.
//Verify
}
}
【问题讨论】:
标签: java spring-boot junit mockito orika