Spring Boot单元测试未拾取模拟控制器的请求映射



我正在尝试测试我的控制器,但控制台说找不到模拟请求的URL映射,我可以看到在发射测试&AMP后,我可以看到控制台上出现的动态映射;他们被映射到各自的方法。

在我的设置中,我有一个模拟服务,该服务被注入了我要测试的控制器中。

这是Test WebApp配置

package com.example.persistance;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.example.dao.UserDao;
import com.example.model.User;
@Configuration
@ComponentScan("com.example")
@EnableWebMvc
class MockWebConfigurationForTest{
    @Bean
    public UserDao setupMockUserDao() {
        User mockUser;
        mockUser=new User();
        mockUser.setId(TestCaseConstants.UserId.uuidAsString());
        mockUser.setAge("24");
        mockUser.setFirstName("Sujal");
        mockUser.setLastName("Mandal");
        mockUser.setUserName("smandal");
        mockUser.setPasswordHash("ABCDE12345");
        UserDao userDao=mock(UserDao.class);
        when(userDao.findOne(TestCaseConstants.UserId.uuidAsString())).thenReturn(mockUser);
        return userDao;
    }
}

这是测试类

package com.example.persistance;
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.example.controllers.UserController;
import com.example.model.User;
import com.google.gson.Gson;
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@ContextConfiguration(classes = {MockWebConfigurationForTest.class})
public class DataPersistenceServiceApplicationTests {
    MockMvc mockMvc;
    String mockUserId=TestCaseConstants.UserId.uuidAsString();
    User mockUser;
    @InjectMocks
    private UserController userController;
    @Before
    public void setUpTestData() {
        mockUser=new User();
        mockUser.setId(mockUserId);
        mockUser.setAge("24");
        mockUser.setFirstName("Sujal");
        mockUser.setLastName("Mandal");
        mockUser.setUserName("smandal");
        mockUser.setPasswordHash("ABCDE12345");
        MockitoAnnotations.initMocks(this);
        mockMvc=MockMvcBuilders.standaloneSetup(UserController.class).build();
    }
    @Test
    public void testUserController_getOne() throws Exception {
        String result=mockMvc.perform(get("/info")).andReturn().getResponse().getContentAsString();
        assertNotNull(result);
    }
}

进行测试时,我会在控制台中看到以下内容。

2018-02-14 11:31:39.912  INFO 9408 --- [           main] p.DataPersistenceServiceApplicationTests : No active profile set, falling back to default profiles: default
2018-02-14 11:31:39.915  INFO 9408 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@427b5f92: startup date [Wed Feb 14 11:31:39 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@1b2abca6
2018-02-14 11:31:40.946  INFO 9408 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=9c2829f3-6e5c-30f7-aeae-06169329e061
2018-02-14 11:31:41.023  INFO 9408 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-02-14 11:31:41.138  INFO 9408 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$4404e8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-14 11:31:41.822  INFO 9408 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-02-14 11:31:41.892  INFO 9408 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:40}] to localhost:27017
2018-02-14 11:31:41.894  INFO 9408 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 2]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, roundTripTimeNanos=597711}
2018-02-14 11:31:42.279  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/info]}" onto public java.lang.String com.example.controllers.InfoController.info()
2018-02-14 11:31:42.282  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[GET]}" onto public java.util.List<com.example.model.User> com.example.controllers.UserController.getAllUsers()
2018-02-14 11:31:42.282  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[PUT]}" onto public com.example.model.User com.example.controllers.UserController.updateOne(com.example.model.User)
2018-02-14 11:31:42.282  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[DELETE]}" onto public void com.example.controllers.UserController.deleteOne(com.example.model.User)
2018-02-14 11:31:42.283  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[POST]}" onto public com.example.model.User com.example.controllers.UserController.saveOne(com.example.model.User)
2018-02-14 11:31:42.283  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/{id}],methods=[GET]}" onto public com.example.model.User com.example.controllers.UserController.getOne(java.lang.String)
2018-02-14 11:31:42.287  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-02-14 11:31:42.288  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-02-14 11:31:42.605  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@427b5f92: startup date [Wed Feb 14 11:31:39 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@1b2abca6
2018-02-14 11:31:43.231  WARN 9408 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-02-14 11:31:43.231  INFO 9408 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-02-14 11:31:43.241  WARN 9408 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-02-14 11:31:43.241  INFO 9408 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-02-14 11:31:44.386  WARN 9408 --- [           main] arterDeprecationWarningAutoConfiguration : spring-cloud-starter-eureka is deprecated as of Spring Cloud Netflix 1.4.0, please migrate to spring-cloud-starter-netflix-eureka
2018-02-14 11:31:44.458  INFO 9408 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2018-02-14 11:31:44.471  INFO 9408 --- [           main] p.DataPersistenceServiceApplicationTests : Started DataPersistenceServiceApplicationTests in 6.268 seconds (JVM running for 7.277)
2018-02-14 11:31:44.674  INFO 9408 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@5ec9eefa
2018-02-14 11:31:44.695  INFO 9408 --- [           main] o.s.mock.web.MockServletContext          : Initializing Spring FrameworkServlet ''
2018-02-14 11:31:44.700  INFO 9408 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
2018-02-14 11:31:44.701  INFO 9408 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 0 ms
==> 2018-02-14 11:31:44.779  WARN 9408 --- [           main] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/info] in DispatcherServlet with name 
2018-02-14 11:31:44.807  INFO 9408 --- [       Thread-5] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@427b5f92: startup date [Wed Feb 14 11:31:39 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@1b2abca6

正如第二行所说的那样,找不到/info的映射,但是如果您在上方看到一点,您可以看到映射成功地拾取了映射,我缺少什么?

我找到了解决方案,我使用了 mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

而不是standaloneSetup()我使用了webApplicationContext的自动实例

package com.example.persistance;
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.example.controllers.UserController;
import com.example.model.User;
import com.google.gson.Gson;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {MockWebConfigurationForTest.class})
public class DataPersistenceServiceApplicationTests {
    @Autowired
    WebApplicationContext webApplicationContext;
    MockMvc mockMvc;
    String mockUserId=TestCaseConstants.UserId.uuidAsString();
    User mockUser;
    @InjectMocks
    private UserController userController;
    @Before
    public void setUpTestData() {
        mockUser=new User();
        mockUser.setId(mockUserId);
        mockUser.setAge("24");
        mockUser.setFirstName("Sujal");
        mockUser.setLastName("Mandal");
        mockUser.setUserName("smandal");
        mockUser.setPasswordHash("ABCDE12345");
        MockitoAnnotations.initMocks(this);
        mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
    @Test
    public void testUserController_getOne() throws Exception {
        Gson gson=new Gson();
        System.err.println("Expected: "+gson.toJson(mockUser));
        String result=mockMvc.perform(get("/users/"+mockUserId)).andReturn().getResponse().getContentAsString();
        System.err.println("Returned: "+result);
        assertNotNull(result);
    }
}

相关内容

  • 没有找到相关文章

最新更新