Конечная точка прослушивания печати, которой управляет Mockito - PullRequest
0 голосов
/ 24 декабря 2018

Я хочу создать тест 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);
}

Я попытался реализовать этот тест JUnit5 с помощью mockito:

@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
@SpringBootTest(classes = PaymentTransactionsController.class)
@WebAppConfiguration
public class PaymentTransactionRepositoryIntegrationTest {
    .....
    private MockMvc mockMvc;

    @MockBean
    private PaymentTransactionRepository transactionRepository;

    @BeforeEach
    void setUp(WebApplicationContext webApplicationContext,
              RestDocumentationContextProvider restDocumentation) {

        PaymentTransactions obj = new PaymentTransactions(1);

        Optional<PaymentTransactions> optional = Optional.of(obj);      

        PaymentTransactionRepository processor = Mockito.mock(PaymentTransactionRepository.class);
        Mockito.when(processor.findById(Integer.parseInt("1"))).thenReturn(optional);       

        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
              .apply(documentationConfiguration(restDocumentation))
              .alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
              .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 transactionsApi() throws Exception {

    PaymentTransactions obj = new PaymentTransactions(1);

    given(target.findById(anyInt())).willReturn(Optional.of(obj));

    this.mockMvc.perform(get("/transactions/{id}", 1)
            .accept("application/xml;charset=UTF-8"))
            .andExpect(status().isOk())
            .andDo(document("Transactions", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()),
                    links(linkWithRel("crud").description("The CRUD resource")),
                    responseFields(subsectionWithPath("_links").description("Links to other resources")),
                    responseHeaders(headerWithName("Content-Type")
                            .description("The Content-Type of the payload, e.g. `application/hal+json`"))));
}
}

Я получаю сообщение об ошибке:

java.lang.AssertionError: Status expected:<200> but was:<404>

Как я могу напечатать конечную точку прослушивания, которая запускается Mockito?Есть ли способ найти его?

Полный вывод: https://pastebin.com/BGGy9E8Z

...