[Unit testing Java] Unit testing Junit Controller
2023-09-14 08:59:13 时间
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
相关文章
- html转word java_word转excel排版不变
- JAVA的除法计算
- java random函数用法_JAVA的Random类的用法详解[通俗易懂]
- java webservice 实例_Java WebService 简单实例(附实例代码)
- java官方编译器_JAVA 编译器
- Java垃圾回收(一)
- java中获取当前时间_java如何获得当前时间
- 解决mysql java.sql.SQLException: The server time zone value‘XXXXXX’ is unrecognized or represents…
- Java接口是什么意思_JAVA接口
- java中如何进行异常处理_java检查时异常
- 第四章Java
- Java岗大厂面试百日冲刺 - 日积月累,每日三题【Day05】——Java高级篇
- 为什么Java项目前会出现一个红色感叹号!详解编程语言
- java抽象类中抽象方法的实现详解编程语言
- 数据库解锁Java,优雅连接Oracle数据库(java使用oracle)
- 深入Linux环境下Java应用调试实践(linux调试java)
- Java调试Linux:探索新的技术可能性(java调试Linux)
- 时间解决Redis Java客户端设置过期时间的方法(redisjava过期)
- 控制Redis为Java实现缓存过期机制(redisjava过期)
- 处理Java处理Redis缓存过期关键技术研究(redisjava过期)
- 检查Java检查Redis中Key的过期状态(redisjava过期)
- 策略设置Redis Java过期策略实现数据缓存功能(redisjava过期)
- Java轻松处理Redis缓存(java处理redis)
- Java调用Linux库实现跨系统功能(java调用linux库)
- 使用Java操作Redis实现高效数据缓存(redisjava使用)
- Learn How to Connect Your Java Application with MongoDB in Just a Few Steps(java连接mongodb)
- 使用Java语言写Redis实现一个分布式缓存系统(用java写个redis)
- 客户端Java客户端快速关闭Redis连接(关闭redis的java)