• [Unit testing Java] Unit testing Junit Controller


    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

  • 相关阅读:
    [Kali_Debian] 清除无用的库文件(清理系统,洁癖专用)-布布扣-bubuko.com
    给 Linux 系统“减肥”,系统垃圾清理_系统安装与配置管理_Linux Today
    命令行选项
    SQL 优化
    精通initramfs构建step by step
    常用正则表达式
    Chrome_浏览器开发人员工具
    按键精灵
    CMD命令大全
    50种折纸方法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14191359.html
Copyright © 2020-2023  润新知