在 SpringBoot 应用之外使用 MockMVC

Use MockMVC outside SpringBoot application

我有一个应用程序使用 Spring MVC 作为 运行 REST 服务(没有 Spring 引导)。上下文主要是从父级加载的。 我有一个控制器,我想通过 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. 您的 pom.xml 中需要 spring-test:

     <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>
    

    不过还是必须的,否则MockMVC会因为没有context而无法启动

  3. 使用以下注释配置您的 ControllerTest class:

     @RunWith(SpringJUnit4ClassRunner.class)
     @ContextConfiguration(locations = "classpath*:testContextConfig.xml")
     @WebAppConfiguration
     public class ControllerTest {        ...    }
    

    没有 @ContextConfigurationMockMVC 将无法工作。

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

     private MockMvc mockMvc;
    
     @Mock
     private Service mockService;
    
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
         mockMvc = MockMvcBuilders.standaloneSetup(new Controller(mockService))
                 .setHandlerExceptionResolvers(exceptionResolver()) //crucial for standaloneSetup of MockMVC
                 .build();
     }
    

    据我所知,setHandlerExceptionResolversmockMVC 设置的关键部分。