【问题标题】:Testing with MockMvc into SpringBoot在 Spring Boot 中使用 MockMvc 进行测试
【发布时间】:2019-02-05 21:04:13
【问题描述】:

我在将 MockMvc 导入 Spring(使用 Spring Boot)时遇到问题。我有一个小代码学习测试

import static org.hamcrest.Matchers.containsString;
import static     org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationTest04_ownServer {

@Autowired
private MockMvc mockMvc;

@Test
public void shouldReturnDefaultMessage() throws Exception {
    this.mockMvc
    .perform(get("/"))
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(content().string(containsString("Hello")));
}

好的。 mi pom.xml是这个

[...]
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.19.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>org.springframework</groupId>
<artifactId>Prueba</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Prueba</name>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>compile</scope>
    </dependency>

</dependencies>

我有几个测试。可行,但我在使用 Mock Object 或类似对象进行测试时遇到问题。例如,在测试中,控制器给我回复一个文本。

@Controller
public class HomeController {

    @RequestMapping("/")
    public @ResponseBody String greeting() {
        return "Hello";
    }

}

在测试中(上面第一个代码),就是这个代码

@Test
public void shouldReturnDefaultMessage() throws Exception {
    this.mockMvc
    .perform(get("/"))
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(content().string(containsString("Hello")));
}

所以,我希望控制器的响应与测试的响应(“hello”)相同,但 Junit 测试是错误的。

java.lang.SecurityException: class "org.hamcrest.Matchers"'s signer information does not match 

我打印结果

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /
       Parameters = {}
          Headers = {}

Handler:
             Type = hello.HomeController
           Method = public java.lang.String hello.HomeController.greeting()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

    ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
         Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[5]}
     Content type = text/plain;charset=UTF-8
             Body = Hello
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /
       Parameters = {}
          Headers = {}

Handler:
             Type = hello.HomeController
           Method = public java.lang.String hello.HomeController.greeting()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[5]}
     Content type = text/plain;charset=UTF-8
             Body = Hello
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

身体反应是你好,不是吗? 有什么想法吗?

观察: 此示例在 Eclipse Neon 中有效,但现在我使用的是 Eclipse 的最新版本。我有很多错误(大多数类型没有出现:MockMvc、SpringRunner、SpringBootTest 等) 解决方案是更改依赖项的范围(测试 --> 编译)。 现在这是依赖项

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>compile</scope>
    </dependency>

会不会和问题有关?

提前致谢

【问题讨论】:

  • 首先,尽可能不要使用war。它的灵活性要差得多,而且特别难以测试。
  • 这是我刚刚所做的更改之一。谢谢

标签: java spring spring-boot testing mocking


【解决方案1】:

依赖的范围应该只是测试。 根据下面的 maven 文档是 scope = test 的描述

  • 测试

此范围表示该依赖不是应用正常使用所必需的,仅适用于测试编译和执行阶段

正如 cmets 中强调的那样,不要使用 war 使用 jar 。您可以删除 tomcat 依赖项,spring boot 将看到 spring web 依赖项并自动提供嵌入式 tomcat。 如果您的意图是仅测试控制器行为,那么您应该使用 Spring Boot 测试切片,在本例中为 Web 切片。所以你可以用 @WebMvcTest 注释你的测试 下面是一个很好的例子,你一定要看看。

https://spring.io/guides/gs/testing-web/

希望对你有帮助

【讨论】:

    【解决方案2】:

    感谢 chryliswhysoseriousson。现在有效

    有了这些想法,我开发了一个新代码(只有Jar到pom.xml中)并且我已经将“测试依赖”的范围设置为“测试”

    [...]
    <packaging>war</packaging>
    [...]
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    

    我遇到了一个附加问题,因为测试文件不在“测试包”中。我已将所有测试文件移至“测试包”。 奇怪的是它在 Neon Eclipse 中工作,而不是在上一个版本中

    我知道 (Test Tutorial of Spring),我的示例中的大部分想法都来自本教程。

    感谢您的回答。问题结束

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 2013-07-06
      • 2015-01-01
      • 2016-11-05
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      相关资源
      最近更新 更多