junit中的TestRestTemplate

时间:2018-04-27 12:00:00

标签: java spring junit

ArticleController.java

    @GetMapping(path = "articles/{article-id}")
    public ResponseEntity<Article> getArticleById( @PathVariable("article-id") Long id) {
    Article article = articleService.findById(id);
    if (article != null)
        return new ResponseEntity<>(article, HttpStatus.OK);
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

ArticleControllerTest.java

public class ArticleControllerTest {

@Autowired
private TestRestTemplate template;

@Test
public void testGetArticle(){
    // how to implement it
}

private HttpEntity<Object> getHttpEntity(Object body) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return new HttpEntity<Object>(body, headers);
}

}

我搜索了很多,但什么都没找到....如何使用模板和这个私有方法实现getArticle?

1 个答案:

答案 0 :(得分:0)

您的控制器对服务类具有依赖性。您要测试的方法是使用articleService.findById(id)方法。通过模拟您的服务类,您可以测试您的控制器。

以下是如何使用MockMvc的示例:

@RunWith(SpringRunner.class)
@WebMvcTest(ProductController.class)
public class ProductControllerMvcTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private ProductService productService;

@Test
public void it_should_return_product_by_id() throws Exception {
    //given
    Long productId = 1L;
    Product product = ProductBuilder.aProduct().id(productId).title("Nokia").build();
    given(productService.findById(productId)).willReturn(product);

    //when
    mockMvc.perform(get("/product/1"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("id").value(productId))
            .andExpect(jsonPath("title").value("Nokia"));
}}