在SpringBoot应用程序之外使用MockMVC

时间:2017-03-31 16:21:19

标签: java rest spring-mvc mockito spring-test-mvc

我有一个使用Spring MVC运行REST服务的应用程序(没有Spring Boot)。上下文主要是从父母那里加载的。 我有一个控制器,我想通过MockMVC进行测试。

我试图用手设置本地测试上下文,但这还不足以进行测试。我假设,我还没有设置额外的bean。

我的控制器是:

@RestController
public class ProrertyEditorController extends AbstractPropertyEditorController {

    @Autowired
    protected PropertyEditorService prorertyEditorService;

    @RequestMapping(method = RequestMethod.DELETE, value = "/{dataType}/deletewithcontent")
@ResponseStatus(value = HttpStatus.OK)
public void deleteWithContent(@PathVariable("dataType") String dataType, @RequestParam("deleteall") boolean deleteAllContent, @RequestBody String node) {
    try {
        JSONArray itemsToDelete = new JSONArray(node);
        prorertyEditorService.deleteItemsWithContent(dataType, itemsToDelete, deleteAllContent);
    } catch (Exception e) {
        //handling exception
    }
}

到目前为止,对控制器的测试看起来像这样:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath*:configBeans1.xml")
public class ProrertyEditorControllerTest{
    private MockMvc mockMvc;

    @Mock
    private PropertyEditorService mockService;
    @InjectMocks
    private ProrertyEditorController controller;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(new ProrertyEditorController()).build();
    }

    @Test
    public void deleteWithContentTest() throws Exception {
                   mockMvc.perform(delete("/full/path/{dataType}/deletewithcontent", type)
                .param("deleteall", "true")
                .param("node", "[{\"test key1\":\"test value1\"}, {\"test keys2\":\"test value2\"}]"));

        verify(mockService, times(1)).deleteItemsWithContent(eq("promotion"), eq(new JSONArray("[{\"test key1\":\"test value1\"}, {\"test keys2\": \"test value2\"}]")), eq(true));
    }

不幸的是,由于

,它无效
Failed to load ApplicationContext

并且没有创建bean

PS有一个选项可以使用

MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();

但是,它需要重构控制器方法,这是不可能的

1 个答案:

答案 0 :(得分:1)

事实证明,绝对有可能这样做。启动它只需要一些配置。

  1. 您需要在pom.xml中进行弹簧测试才能使其正常工作

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
    </dependency>
    
  2. 创建testContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    </beans>
    
  3. 尽管如此,它仍然是必需的,否则,MockMVC将无法启动,因为没有上下文。

    1. 使用以下注释为您的controllerTest课程配置:

      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(locations = "classpath*:testContextConfig.xml")
      @WebAppConfiguration
      public class ControllerTest {        ...    }
      
    2. 我应该提到,@ContextConfiguration MockMVC没有工作。

      1. MockMVC方法中创建@Before个实例:

        private MockMvc mockMvc;
        
        @Mock
        private Service mockService;
        
        @Before
        public void setup() {
            MockitoAnnotations.initMocks(this);
            mockMvc = MockMvcBuilders.standaloneSetup(new Controller(mockService))
                    .setHandlerExceptionResolvers(exceptionResolver()) //crutial for standaloneSetup of MockMVC
                    .build();
        }
        
      2. 据我所知,setHandlerExceptionResolversmockMVC设置的重要组成部分。

        基本上就是这样。