【问题标题】:Spring Boot 1.4 TestingSpring Boot 1.4 测试
【发布时间】:2016-10-29 22:17:15
【问题描述】:

我是 Spring Boot 1.4 测试的新手,正在尝试使用新功能。我有一个简单的 Spring MVC 控制器。

@Controller
public class IndexController {
  @RequestMapping("/")
  String index(){
    return "index";
  }
}

控制器返回一个 Thymeleaf 模板,其中包含字符串 Hello

我已经编写了以下单元测试并且运行良好:

@RunWith(SpringRunner.class)
@WebMvcTest(IndexController.class)
public class SpringMvcTestApplicationTests {


private MockMvc mockMvc;
@Before
public void setUp() {
    mockMvc = MockMvcBuilders.standaloneSetup(new  IndexController()).build();
}

@Test
public void testIndex() throws Exception{

    MvcResult result= this.mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index"))
            .andReturn();
    String content = result.getResponse().getContentAsString();
    assertNotNull(content);
  }
}

但我读过许多注释提供了特定于测试的额外自动配置。例如,如果您使用@WebMvcTest,您可以@Autowire 一个完全配置的MockMvc 实例。。我还看到了自动装配 MockMvc 的示例。

但是当我在删除@Before方法后添加下面的自动装配代码时,测试失败了。

@Autowired
private MockMvc mockMvc;

断言错误是:

java.lang.AssertionError: Status 
Expected :200
Actual   :401

第二个问题是,我想测试一下 Thymeleaf 返回的内容。我测试过:

.andExpect(content().string("Hello"))

还有

.andExpect(content().string(Matchers.containsString("Hello")))

还有

assertEquals("Hello", content);

在检查时,我发现内容是一个空字符串,因此测试失败:

org.junit.ComparisonFailure: 
Expected :Hello
Actual   :

如何测试内容。

提前致谢。

【问题讨论】:

    标签: spring-mvc thymeleaf spring-test-mvc


    【解决方案1】:

    第一期:

    使用@WebMvcTest 自动装配您的 MockMvc 的问题在于,它似乎默认启用了安全性(请参阅https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html),这导致您的 401 Unauthorized 断言状态代码,因为“/”的 GET 请求未通过安全检查。对于您的简单情况,坚持使用“MockMvcBuilders.standaloneSetup()”来创建您的 MockMvc 可能是最简单的。

    您可以添加一个单行注释(确保也导入包)以防止 MockMvc 安全性:

    @WebMvcTest(IndexController.class)
    @AutoConfigureMockMvc(secure=false)
    public class IndexControllerTest {
    

    【讨论】:

    • 你是对的,这是由于安全问题。我正在专门研究如何使用 WebMvcTest 注释自动装配 MockMvc。有几篇文章展示了它,但我无权访问源代码。几个例子是 Official version here(测试 Spring MVC 切片)、hereand also here
    • 问题依然存在。我已经在 GitHub 上发布了代码 [点击这里] (github.com/ximanta/blog-spring-mvc-test)
    • 知道了,也看到了同样的问题,所以它不像我想象的那么简单。废弃该安全配置,您可以使用我在上次编辑中发布的单行注释来修改 MockMvc 的默认自动配置。这允许 IndexControllerTest 现在为我通过。
    • 你不需要@AutoConfigureMockMvc(secure=false),你可以使用@WebMvcTest(controllers = IndexController.class, secure = false)
    • @AutoConfigureMockMvc(secure=false)@AutoConfigureMockMvc(secure=false) 都适用于 mockMvc.perform(get("/"))。但对于不同的 URL,比如mockMvc.perform(get("/products"))mockMvc.perform(get("product/{id}", 1)).andExpect(status().isOk()) 中会出现Status 断言错误。可能是什么原因?
    猜你喜欢
    • 2017-04-23
    • 2016-12-05
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2016-10-31
    • 2023-03-23
    • 2016-11-05
    相关资源
    最近更新 更多