Я хочу создать тест 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) {
String hql = "select e from " + PaymentTransactions.class.getName() + " e where e.id = :id";
TypedQuery<PaymentTransactions> query = entityManager.createQuery(hql, PaymentTransactions.class).setParameter("id", id);
List<PaymentTransactions> paymentTransactions = query.getResultList();
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();
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
PaymentTransactionRepository target;
@Autowired
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@MockBean
private PaymentTransactionRepository transactionRepository;
@BeforeEach
void setUp() {
Optional<PaymentTransactions> optional = Optional.of(new PaymentTransactions());
when(transactionRepository.findById(Integer.parseInt("1"))).thenReturn(optional);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
PaymentTransactionRepository tnx = Mockito.mock(PaymentTransactionRepository.class);
ReflectionTestUtils.setField(PaymentTransactionsController.class, "PaymentTransactionRepository", tnx);
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation)).build();
}
@Test
public void testNotNull() {
assertNotNull(target);
}
@Test
public void testFindByIdFound() {
Optional<PaymentTransactions> res = target.findById((int) 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();
}
}
}
Я получаю сообщение об ошибке для when
:
The method when(Optional<PaymentTransactions>) is undefined for the type PaymentTransactionRepositoryIntegrationTest
Знаете ли вы, как правильно реализовать пробный тест?