简体   繁体   English

使用MockMvc测试SpringBoot

[英]Testing with MockMvc into SpringBoot

I have a problem with MockMvc into Spring (with Spring Boot). 我对MockMvc到Spring(使用Spring Boot)有问题。 I have a small code to learn Testing 我有一个小代码来学习测试

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")));
}

OK. 好。 Mi pom.xml is this 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>

I have several test. 我有几次测试。 The works, but I have a problem with test with Mock Object or similar. 的作品,但我对模拟对象或类似的测试有问题。 For example, in the test, the controller response me a text. 例如,在测试中,控制器向我回复了一条文本。

@Controller
public class HomeController {

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

}

In the test (the first code above), this is the code 在测试中(上面的第一个代码),这是代码

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

So, I expect that the response of controller was the same that the response of the test ("hello") but the Junit test is wrong. 因此,我希望控制器的响应与测试(“ hello”)的响应相同,但是Junit测试是错误的。

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

I print the result 我打印结果

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 = []

The body response is hello, isn`t is? 身体反应是你好,不是吗? Any idea? 任何想法?

Observation: This example works in Eclipse Neon but now I use the last version of Eclipse. 观察:该示例在Eclipse Neon中有效,但是现在我使用的是Eclipse的最新版本。 I had a lot of error (the most of type don't appear: MockMvc, SpringRunner, SpringBootTest, etc.) The solution was to change the scope of the dependency (test --> compile). 我有很多错误(大多数类型不会出现:MockMvc,SpringRunner,SpringBootTest等)。解决方案是更改依赖项的范围(测试->编译)。 Now this is the dependency 现在这是依赖

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

Can it have something to do with the problem? 它可以与问题有关吗?

Thanks in advance 提前致谢

The scope of dependency should be test only. 依赖范围应该仅是测试。 As per maven documentation below is the description for scope = test 根据下面的Maven文档,范围=测试的描述

  • test 测试

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases 此范围表明依赖关系对于正常使用应用程序不是必需的,并且仅在测试编译和执行阶段可用

As highlighted in comments , dont use war use jar .You can remove tomcat dependency as well as spring boot will see spring web dependency and would provide embedded tomcat automatically. 如评论中突出显示的那样,不要使用war use jar。您可以删除tomcat依赖项,并且spring boot会看到spring Web依赖项并会自动提供嵌入式tomcat。 If your intention is to test only the controller behavior, then you should use spring boot test slices, in this case web slice. 如果您打算仅测试控制器行为,则应使用Spring Boot测试片,在这种情况下为Web片。 So you can annotate your test with @WebMvcTest Below is an excellent example and u should definitely check this out. 因此,您可以使用@WebMvcTest注释测试,以下是一个很好的示例,您绝对应该检查一下。

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

Hope this helps 希望这可以帮助

Thanks to chrylis and whysoseriousson . 多亏克莱里斯Whysoseriousson Now works 现在可以使用

With these ideas, I have developed a new code (only Jar into pom.xml) and I have set the scope of "test dependency" to "test" 有了这些想法,我开发了一个新代码(只有Jar放入pom.xml中),并且将“测试依赖项”的范围设置为“测试”

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

I had an aditional problem because the test file wasn't into the "test package". 我遇到了一个附加的问题,因为测试文件未放入“测试包”中。 I have moved all the test files to "test package". 我已将所有测试文件移至“测试包”。 It's curiosus that it worked into Neon Eclipse and not in last version 好奇的是它适用于Neon Eclipse,而不是最新版本

I knew the ( Test Tutorial of Spring ) and the most of ideas of my example are of this tutorial. 我知道( Spring的Test Tutorial ),并且我的示例中的大部分思想都属于本教程。

Thanks for the answer. 感谢您的回答。 Question closed 问题已关闭

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM