Controller:
@RestController @RequestMapping(path = "/ratings") public class RatingController { private static final Logger LOGGER = LoggerFactory.getLogger(RatingController.class); private TourRatingService tourRatingService; private RatingAssembler assembler; @Autowired public RatingController(TourRatingService tourRatingService, RatingAssembler assembler) { this.tourRatingService = tourRatingService; this.assembler = assembler; } @GetMapping public List<RatingDto> getAll() { LOGGER.info("GET /ratings"); return assembler.toResources(tourRatingService.lookupAll()); } @GetMapping("/{id}") public RatingDto getRating(@PathVariable("id") Integer id) { LOGGER.info("GET /ratings/{id}", id); return assembler.toResource(tourRatingService.lookupRatingById(id) .orElseThrow(() -> new NoSuchElementException("Rating " + id + " not found")) ); } /** * Exception handler if NoSuchElementException is thrown in this Controller * * @param ex exception * @return Error message String. */ @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(NoSuchElementException.class) public String return400(NoSuchElementException ex) { LOGGER.error("Unable to complete transaction", ex); return ex.getMessage(); } }
We don't want to use real TourRatingService, we want to inject mock service.
/** * Invoke the Controller methods via HTTP. * Do not invoke the tourRatingService methods, use Mock instead */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT) public class RatingControllerTest { private static final String RATINGS_URL = "/ratings"; //These Tour and rating id's do not already exist in the db private static final int TOUR_ID = 999; private static final int RATING_ID = 555; private static final int CUSTOMER_ID = 1000; private static final int SCORE = 3; private static final String COMMENT = "comment"; @MockBean private TourRatingService tourRatingServiceMock; @Mock private TourRating tourRatingMock; @Mock private Tour tourMock; @Autowired private TestRestTemplate restTemplate; @Before public void setupReturnValuesOfMockMethods() { when(tourRatingMock.getTour()).thenReturn(tourMock); when(tourMock.getId()).thenReturn(TOUR_ID); when(tourRatingMock.getComment()).thenReturn(COMMENT); when(tourRatingMock.getScore()).thenReturn(SCORE); when(tourRatingMock.getCustomerId()).thenReturn(CUSTOMER_ID); } /** * HTTP GET /ratings */ @Test public void getRatings() { when(tourRatingServiceMock.lookupAll()).thenReturn(Arrays.asList(tourRatingMock, tourRatingMock, tourRatingMock)); ResponseEntity<List<RatingDto>> response = restTemplate.exchange(RATINGS_URL, HttpMethod.GET,null, new ParameterizedTypeReference<List<RatingDto>>() {}); assertThat(response.getStatusCode(), is(HttpStatus.OK)); assertThat(response.getBody().size(), is(3)); } /** * HTTP GET /ratings/{id} */ @Test public void getOne() { when(tourRatingServiceMock.lookupRatingById(RATING_ID)).thenReturn(Optional.of(tourRatingMock)); ResponseEntity<RatingDto> response = restTemplate.getForEntity(RATINGS_URL + "/" + RATING_ID, RatingDto.class); assertThat(response.getStatusCode(), is(HttpStatus.OK)); assertThat(response.getBody().getCustomerId(), is(CUSTOMER_ID)); assertThat(response.getBody().getComment(), is(COMMENT)); assertThat(response.getBody().getScore(), is(SCORE)); }
https://github.com/zhentian-wan/spring-path/tree/master/explorecali/src/test/java/com/example/ec