在Spring Boot中进行单元测试,但由于转换器类而出错

问题描述 投票:0回答:1

我使用转换器类,在单元测试中出现空指针异常错误。但是我用return accountDto代替了转换器类它正在运行。代码正在邮递员处运行。请给我一些建议。

@Test
void store() {
    Date date = new Date();
    Account accountMock = mock(Account.class);
    AccountDto accountDto = new AccountDto();
    accountDto.setId(randomUUID);
    accountDto.setName("Test-Name");
    accountDto.setSurname("Test-Lastname");
    accountDto.setEmail("Test-Email");
    accountDto.setBirth_date(date);
    accountDto.setPassword("Test-Email");
    accountDto.setStatus(OPEN);

    when(accountMock.getId())
       .thenReturn(String.valueOf(randomUUID));
    when(accountRepository.save(ArgumentMatchers.any(Account.class)))
       .thenReturn(accountMock);

    AccountDto result = accountService.store(accountDto);

    assertEquals(result.getName(), accountDto.getName());
    assertEquals(result.getId(), String.valueOf(randomUUID));
}

服务方法=>

@Transactional
public AccountDto store(AccountDto accountDto) {
    Account account = new Account();
    account.setName(accountDto.getName());
    account.setSurname(accountDto.getSurname());
    account.setEmail(accountDto.getEmail());
    account.setBirth_date(accountDto.getBirth_date());
    account.setPassword(accountDto.getPassword());
    account.setStatus(accountDto.getStatus());
    final Account accountDb = repository.save(account);
    accountDto.setId(accountDb.getId());

    return converter.convertFromEntity(accountDb);
}

转换器类=>

 /**
 * Converts Entity to DTO.
 *
 * @param entity domain entity
 * @return The DTO representation - the result of the converting function application on domain
 * entity.
 */
public final T convertFromEntity(final U entity) {
    return fromEntity.apply(entity);
}

错误=>

java.lang.NullPointerException
at com.kablanfatih.tddexample.converter.Converter.convertFromEntity(Converter.java:51)
at com.kablanfatih.tddexample.service.impl.AccountServiceImpl.store(AccountServiceImpl.java:42)
at com.kablanfatih.tddexample.service.impl.AccountServiceImplTest.store(AccountServiceImplTest.java:87)
java spring-boot unit-testing junit tdd
1个回答
0
投票

我认为您有两个选择。首先,您可以模拟Converter类,其次,您可以正确地初始化转换器并在测试中使用它。我更喜欢第一个解决方案,因为我可以控制Converter的行为。

© www.soinside.com 2019 - 2024. All rights reserved.