预期状态:< 200>但是:< 404>在春季测试

时间:2013-10-02 13:38:19

标签: java spring testing spring-mvc mocking

我有这堂课:

    package controllers;

    import static org.junit.Assert.*;
    import static org.mockito.Mockito.mock;
    import static org.mockito.Mockito.times;
    import static org.mockito.Mockito.verify;
    import static org.mockito.Mockito.when;

    import java.util.HashSet;

    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.MockitoAnnotations;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;


    import org.springframework.ui.Model;
    import org.springframework.web.context.WebApplicationContext;

    import com.epam.hhsystem.model.candidate.Candidate;
    import com.epam.hhsystem.services.CandidateService;
    import com.epam.hhsystem.web.controllers.CandidateMenuController;
    import org.springframework.test.context.web.WebAppConfiguration;
    import org.springframework.test.context.junit4.*;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.ResultActions;
    import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;


    import org.springframework.test.web.servlet.request.*;

    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
    import static org.hamcrest.Matchers.*;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;


    @ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    public class CandidateControllerTest {

        @Mock(name = "candidateService")
        private CandidateService candidateService;

        @InjectMocks
        private CandidateMenuController candidateMenuController = new CandidateMenuController();

        @Autowired
        WebApplicationContext wac;

        MockMvc mockMvc;

        @Before
        public void before() {
            MockitoAnnotations.initMocks(this);
              this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();

        }
@Test 
    public void testgoToCandidateMenuMockMvc() throws Exception { 
        //MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu");


        MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu");
        ResultActions result = mockMvc.perform(request);
        result.andExpect(status().isOk());
     }
}

当我执行它时,我看到:

java.lang.AssertionError: Status expected:<200> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:549)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at controllers.CandidateControllerTest.testgoToCandidateMenuMockMvc(CandidateControllerTest.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

控制器代码:

@Controller
public class CandidateMenuController extends AbstractController {
...
@RequestMapping("/goToCandidateMenu")
    public String goToCandidateMenu() {
        return "candidateMenu";
    }
...
}

你能帮我解决问题吗?

更新

BeanConfig.xml:

 <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
        xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
            http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

        <!-- Включаем опцию использования конфигурационных аннотаций (@Annotation-based configuration)-->
        <context:annotation-config />


        <context:component-scan base-package="com.epam.hhsystem.jpa" />
        <context:component-scan base-package="com.epam.hhsystem.services" />

        <!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) -->
        <import resource="data.xml" />

    </beans>

data.xml中

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<!-- Настраивает управление транзакциями с помощью аннотации @Transactional -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Менеджер транзакций -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Непосредственно бин dataSource -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
        p:url="jdbc:sqlserver://10.16.9.52:1433;databaseName=hhsystemTest;"
        p:username="userNew" 
        p:password="Pass12345" />

    <!-- Настройки фабрики сессий Хибернейта -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:test/hibernate.cfg.xml</value>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
<!--                <prop key="hibernate.hbm2ddl.auto">create-drop</prop> -->
        </props>
        </property>
    </bean>

</beans>

10 个答案:

答案 0 :(得分:6)

您的测试设置错误,您没有正确初始化MockMvc,这在参考指南中很清楚。首先,你有两倍的初始化代码,而你没有得到调用build方法的结果。所以你基本上留下了一个空的MockMvc对象。

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}

应该是

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}

如上所述,这一切都在the reference guide中解释。

答案 1 :(得分:4)

我相信您<mvc:annotation-driven>尚未启用beanconfig.xml,因此您的@Controller课程尚未注册。

添加此

<mvc:annotation-driven></mvc:annotation-driven>

答案 2 :(得分:2)

这是我的工作解决方案。希望它有所帮助。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class SimpleTest  {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext webApplicationContext;

@Before
public void setup() throws Exception {
    mockMvc = webAppContextSetup(webApplicationContext)
            .build();
    }

@Test
public void test() throws Exception {        
    mockMvc.perform(get("/simple")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().is(200));
    }
}

答案 3 :(得分:2)

就我而言,我缺少以下注释,并且遇到了此错误。

@WebMvcTest(UserStatsController.class)
public class UserStatsControllerTest {
  ..
}

请注意,控制器的类别为不进行测试。 同样,如果使用@ContextConfiguration(不测试)加载其他类,请确保不要加载测试类。

答案 4 :(得分:1)

我将此注释添加到配置类并使用它:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
public class ResourceTest {

   ...

   @Configuration
   @EnableWebMvc
   @ComponentScan( basePackages = { "..." } )
   static class ContextConfiguration {
   }
}

答案 5 :(得分:1)

我的问题是我没有@ComponentScan(),这真令人尴尬。 这也很难找到。我自己忽略了我的SpringBootApplication。

答案 6 :(得分:0)

如果像我一样做一个非常愚蠢的“为了自己的利益而努力斋戒”错字,请确保您的控制器测试类的名称与控制器类本身的名称不同。大多数人都知道这一点,但是您可能会遇到相同的错误情况,它们的名称是相同的,这也许不是我立即明白的原因。为了进一步说明,请确保您不这样做:

控制器名称:MyController
测试类名称:MyController

这可能会导致您的MockMvc测试失败,状态为404 ...这不是很明显。
命名(显然)应该更像是:

控制器名称:MyController
测试类名称:MyControllerTest

答案 7 :(得分:0)

以下是我在春季MVC中所做的工作,效果很好(解释为无法找到直接参考) 控制器类为以下

            package rndpurpose.controller;

            @RestController
            @RequestMapping("/springmvc")
            public class urlController {

                @CrossOrigin
                @RequestMapping(value = "managepostReq", method = RequestMethod.POST, headers = "Accept=application/json")
                public Map<String, Object> managepostReq()
                {
                    Map<String, Object> response = new HashMap<>();

                    //System.out.println(data);
                    response.put("status", true);

                    return response;
                }
            }

在rndpurpose.text(程序包)内部>创建的程序包与WebConfig.java中我的@ComponentScan所创建的程序包相关

            package rndpurpose.test;

            import static org.hamcrest.Matchers.is;
            import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
            import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
            import org.json.JSONObject;
            import org.junit.Test;
            import org.springframework.core.annotation.Order;
            import org.springframework.test.web.servlet.MvcResult;
            import org.springframework.test.web.servlet.ResultActions;
            import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
            import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
            import junit.framework.Assert;

            public class UrlcontrollerTest extends JunitAbstract {

                @Test
                @Order(1)
                public void firsttestcase() throws Exception {
                /*jai ganesha*/
                    try {
                        JSONObject jsonGetData = new JSONObject();
                        jsonGetData.put("username", "name");
                        
                        ResultActions resultActions = postRequest("/springmvc/managepostReq", jsonGetData.toString());
                        MvcResult mvcResult = resultActions.andExpect(status().isOk())
                                .andDo(MockMvcResultHandlers.print())
                                .andReturn();

                        
                        JSONObject reqResponse = new JSONObject(mvcResult.getResponse().getContentAsString());
                        System.out.println(reqResponse);

                    } catch (Exception e) {
                        System.err.println("ERROR"+ e);
                    }
                }

            }

和用于处理请求的JunitAbstract

            package rndpurpose.test;
            import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
            import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
            import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
            import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
            import java.lang.reflect.InvocationTargetException;
            import java.nio.charset.Charset;
            import org.junit.Before;
            import org.junit.runner.RunWith;
            import org.mockito.MockitoAnnotations;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.context.annotation.ComponentScan;
            import org.springframework.http.MediaType;
            import org.springframework.mock.web.MockMultipartFile;
            import org.springframework.test.context.ContextConfiguration;
            import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
            import org.springframework.test.context.web.WebAppConfiguration;
            import org.springframework.test.web.servlet.MockMvc;
            import org.springframework.test.web.servlet.ResultActions;
            import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
            import org.springframework.test.web.servlet.setup.MockMvcBuilders;
            import org.springframework.util.MultiValueMap;
            import org.springframework.web.context.WebApplicationContext;
            import rndpurpose.config.WebConfig;
            @RunWith(SpringJUnit4ClassRunner.class)
            @ContextConfiguration(classes = WebConfig.class)
            @WebAppConfiguration
            @ComponentScan(basePackages="rndpurpose")
            public abstract class JunitAbstract {

                public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

                private MockMvc mockMvc;

                @Autowired
                public WebApplicationContext wac;


                @Before
                public void setup() {
                    MockitoAnnotations.initMocks(this);
                    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
                }

                public ResultActions postRequest(String url, String bodyData) {
                    ResultActions resultActions = null;
                    try {
                        System.out.println(url);
                        resultActions = mockMvc.perform(post(url).contentType(MediaType.APPLICATION_JSON)
                                .accept(MediaType.APPLICATION_JSON).content(bodyData));
                                
                    }
                    
                    catch (InvocationTargetException e) {
                        e.getCause().printStackTrace();
                    } 
                    catch (Exception e) {
                        System.err.println("Error while executing post req "+ e);
                    }
                    return resultActions;
                }

                public ResultActions getRequest(String url) {
                    ResultActions resultActions = null;
                    try {
                        resultActions = this.mockMvc.perform(get(url)).andDo(print());
                    } catch (Exception e) {
                        System.err.println("Error while executing test case for get"+ e);
                    }
                    return resultActions;
                }

                public ResultActions multipartFileUpload(String url, MultiValueMap<String, String> bodyMap,
                        MockMultipartFile... files) {
                    ResultActions resultActions = null;
                    try {
                        MockMultipartHttpServletRequestBuilder builder = multipart(url);
                        addMultipartFiles(builder, files);
                        if (bodyMap != null)
                            builder.params(bodyMap);
                        resultActions = mockMvc.perform(builder);
                    } catch (Exception e) {
                        System.err.println("Error in multipartFileUpload "+ e);
                    }
                    return resultActions;
                }

                private void addMultipartFiles(MockMultipartHttpServletRequestBuilder builder, MockMultipartFile... files) {
                    if (files != null) {
                        for (MockMultipartFile file : files) {
                            builder.file(file);
                        }
                    }

                }

            }

和pom看起来像这样

    <!-- test starts -->


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.1.2.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>


    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>2.23.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-runner</artifactId>
        <version>1.2.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.8.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>1.10.19</version>
        <exclusions>
            <exclusion>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-core</artifactId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.0.0</version>
    </dependency>

    <!-- test ends -->

答案 8 :(得分:0)

在我的情况下,我在MyApplication类上缺少@ComponentScan(“ my.package。*”),因为我的控制器与MyApplication类位于不同的包中。

请在调试模式下检查调试器的刻度线。如果正在扫描组件,它将显示为刻度线,否则不会。

enter image description here

答案 9 :(得分:0)

在未加载我的控制器时遇到类似的错误,如果使用基于.xml的分派器servlet的spring mvc,我可以通过添加@ContextConfiguration来修复它 如下

有一个Bean连接数据库

@EnableWebMvc
public class WebConfig  {

private static final Logger LOGGER = Logger.getLogger(WebConfig.class);

@Bean
public CommonsMultipartResolver multipartResolver() {
    final CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setMaxUploadSize(20971520);
    resolver.setMaxInMemorySize(1048576);
    return resolver;
}
@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    
     dataSource.setUrl("jdbc:postgresql://192.168.2.29:5432/trintiygisenterprise");
     dataSource.setDriverClassName("org.postgresql.Driver");
     dataSource.setUsername("postgres"); 
     dataSource.setPassword("track@123");
     
    return dataSource;
}

@Bean
public Connection getConnectionObject() {
    Connection con  = null;
    try {
        Class.forName("org.postgresql.Driver");

         con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/t26",
                 "postgres", "track@123");

         System.out.println("====================CONNECTED TO DB================ "+con);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);
    }
    return con;

}

@Bean
@Autowired
public JdbcTemplate jdbcTemplate(DataSource dataSource) {

    return new JdbcTemplate(dataSource);
}
}

,它将在springrest-servlet.xml中扫描

<context:component-scan base-package="com" />
 <mvc:annotation-driven />  
<!--  <mvc:resources mapping="/*" location="/" />-->

<mvc:default-servlet-handler/>
<bean class="com.config.WebConfig"/>
</beans>

和web.xml

    <servlet>
    <servlet-name>springrest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springrest</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

控制器看起来像这样

@RestController
@RequestMapping("/api")
public class bootsrapController {


/**
@GetMapping("/second")
**/
@RequestMapping(value = "second", method = RequestMethod.GET, headers = 
"Accept=application/json")
public Map<String, Object> second() 
{
    Map<String, Object> result = new HashMap<>();
    result.put("second", true);
    result.put("status", true);
return result;
}
}

Testcontroller如下

public class UrlcontrollerTest extends JunitAbstract {
    @Test
@Order(1)
public void unittestcreatelayergroup(){

    try {

        System.out.println("Running test");
        
        final ResultActions resultActions = getRequest("/api/second");
        System.out.println(resultActions);
        
        final MvcResult mvcResult = resultActions
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("status", is(true)))
                .andReturn(); 
}
    catch (final Exception e) {

        LOGGER.error(e.getStackTrace());

    }
}

和获取要求的单元测试如下

@ContextConfiguration("file:src/main/webapp/WEB-INF/springrest-servlet.xml") 
@WebAppConfiguration
public abstract class JunitAbstract {

private static final Logger LOGGER = Logger.getLogger(JunitAbstract.class);

private MockMvc mockMvc;

@Autowired
public WebApplicationContext wac;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

public ResultActions getRequest(String url) {
    LOGGER.info("sending req--------: "+url);

    ResultActions resultActions = null;
    try {
        resultActions = this.mockMvc.perform(get(url)).andDo(print());
    } catch (Exception e) {
        LOGGER.error("Error while executing test case for get"+ e);
    }
    return resultActions;
}

也感谢@tunguski的答案enter link description here

enter image description here