I have this quite simple controller class and a simple (jpa) repository. What I want to do is to test it's api but mock it's repository and let it return an object or not depending on the test case.
My problem now is that I don't know how to do that.
I know how to mock a repository and inject it to a controller/service class with @Mock / @InjectMocks / when().return()
But I fail when I want to do the same after doing a request with MockMvc. Any help is highly appreciated
The controller
import java.util.Optional;
@RestController
@Slf4j
public class ReceiptController implements ReceiptsApi {
@Autowired
private ReceiptRepository receiptRepository;
@Autowired
private ErrorResponseExceptionFactory exceptionFactory;
@Autowired
private ApiErrorResponseFactory errorResponseFactory;
@Override
public Receipt getReceipt(Long id) {
Optional<ReceiptEntity> result = receiptRepository.findById(id);
if (result.isEmpty()) {
throw invalid("id");
}
ReceiptEntity receipt = result.get();
return Receipt.builder().id(receipt.getId()).purchaseId(receipt.getPurchaseId()).payload(receipt.getHtml()).build();
}
private ErrorResponseException invalid(String paramName) {
return exceptionFactory.errorResponse(
errorResponseFactory.create(HttpStatus.NOT_FOUND.value(), "NOT_VALID", String.format("receipt with id %s not found.", paramName))
);
}
}
And it's test class
@WebMvcTest(ReceiptController.class)
@RestClientTest
public class ReceiptControllerTest {
@InjectMocks
private ReceiptController receiptController;
@Mock
private ReceiptRepository receiptRepository;
@Mock
private ErrorResponseExceptionFactory exceptionFactory;
@Mock
private ApiErrorResponseFactory errorResponseFactory;
private MockMvc mvc;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(
new ReceiptController())
.build();
}
@Test
public void getReceiptNotFoundByRequest() throws Exception {
mvc.perform(MockMvcRequestBuilders
.get("/receipt/1")
.header("host", "localhost:1348")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
//TODO: Finish this test
@Test
public void getReceiptFoundByRequest() throws Exception {
ReceiptEntity receipt1 = ReceiptEntity.builder().id(99999L).purchaseId(432L).html("<html>").build();
when(receiptRepository.findById(1L)).thenReturn(Optional.of(ReceiptEntity.builder().id(1L).purchaseId(42L).html("<html></html>").build()));
ResultActions result = mvc.perform(get("/receipt/1")
.header("host", "localhost:1348")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}