下面测试源码中的status()函数出现错误。由于源代码中没有 status() 函数,因此出现错误是很自然的。但是,我没有在书籍或互联网上的源代码中看到创建单独的函数。调用 status() 函数需要什么?
package kr.jhansol.blog.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import kr.jhansol.blog.dto.AddArticleRequest;
import kr.jhansol.blog.repository.BlogRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@SpringBootTest
@AutoConfigureMockMvc
class BlogApiControllerTest {
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@Autowired
private WebApplicationContext context;
@Autowired
BlogRepository blogRepository;
@BeforeEach
public void mockMvcSetUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
blogRepository.deleteAll();
}
@DisplayName("Blog write test")
@Test
public void addArticle() throws Exception {
final String url = "/api/articles";
final String title = "test";
final String content = "This is test.";
final AddArticleRequest request = new AddArticleRequest(title, content);
final String requestBody = objectMapper.writeValueAsString(request);
ResultActions result = mockMvc.perform(post(url)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(requestBody));
result.andExpect(status().isCreated());
}
}
执行上述代码时,输出以下错误。
D:\spring_projects\blog\src\test\java\kr\jhansol\blog\controller\BlogApiControllerTest.java:55: error: cannot find symbol
result.andExpect(status().isCreated());
^
symbol: method status()
location: class BlogApiControllerTest
解决了。 我将下面的代码添加到上面源代码的顶部。
导入静态org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;