Я хочу создать тест JUnit для Rest api и сгенерировать api doc.Я хочу проверить этот код:
Контроллер покоя
@RestController
@RequestMapping("/transactions")
public class PaymentTransactionsController {
@Autowired
private PaymentTransactionRepository transactionRepository;
@GetMapping("{id}")
public ResponseEntity<?> get(@PathVariable String id) {
return transactionRepository
.findById(Integer.parseInt(id))
.map(mapper::toDTO)
.map(ResponseEntity::ok)
.orElseGet(() -> notFound().build());
}
}
Интерфейс репозитория
public interface PaymentTransactionRepository extends CrudRepository<PaymentTransactions, Integer>, JpaSpecificationExecutor<PaymentTransactions> {
Optional<PaymentTransactions> findById(Integer id);
}
Impl репозитория:
@Service
@Qualifier("paymentTransactionService")
@Transactional
public class PaymentTransactionRepositoryImpl implements PaymentTransactionRepository {
@Override
public Optional<PaymentTransactions> findById(Integer id) {
.......
return paymentTransactions.isEmpty() ? Optional.empty() : Optional.of(paymentTransactions.get(0));
}
}
Я пыталсяреализовать этот тест JUnit5 с mockito:
@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
@SpringBootTest(classes = PaymentTransactionsController.class)
@WebAppConfiguration
public class PaymentTransactionRepositoryIntegrationTest {
public final ManualRestDocumentation restDocumentation = new ManualRestDocumentation();
private MockMvc mockMvc;
@MockBean
private PaymentTransactionRepository transactionRepository;
@BeforeEach
void setUp() {
Optional<PaymentTransactions> optional = Optional.of(new PaymentTransactions());
PaymentTransactionRepository processor = Mockito.mock(PaymentTransactionRepository.class);
Mockito.when(processor.findById(Integer.parseInt("1"))).thenReturn(optional);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation)).build();
}
@Test
public void testNotNull() {
assertNotNull(target);
}
@Test
public void testFindByIdFound() {
Optional<PaymentTransactions> res = target.findById(Integer.parseInt("1"));
// assertTrue(res.isPresent());
}
@Test
public void uniqueTransactionIdLenght() {
try {
this.mockMvc.perform(RestDocumentationRequestBuilders.get("/transactions/1")).andExpect(status().isOk())
.andExpect(content().contentType("application/xml;charset=UTF-8"))
.andDo(document("persons/get-by-id"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Но я получаю NPE:
2018-12-23 15:31:10.411 INFO 48843 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 35 ms
java.lang.NullPointerException org.datalis.admin.restapi.PaymentTransactionRepositoryIntegrationTest.uniqueTransactionIdLenght(PaymentTransactionRepositoryIntegrationTest.java:96)
В этой строке: this.mockMvc.perform(RestDocumentationRequestBuilders.get("/transactions/1")).andExpect(status().isOk())
Вы знаете, как я могу решитьЭта проблема?Возможно, моя конфигурация неверна?
Полный стек ошибок: https://pastebin.com/U5GzjAQ4