在 SpringBoot 应用程序之外使用 MockMVC

ryz*_*man 4 java rest spring-mvc mockito spring-test-mvc

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

我尝试手动设置本地测试上下文,但这不足以运行测试。我想,应该还有我没有设置的额外豆子。

我的控制器是:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,控制器的测试如下所示:

@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));
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不起作用,因为

Failed to load ApplicationContext
Run Code Online (Sandbox Code Playgroud)

并且没有创建任何bean

PS 有一个选项可以使用

MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Run Code Online (Sandbox Code Playgroud)

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

ryz*_*man 5

事实证明,完全有可能做到。启动它只需要一些配置。

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

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    Run Code Online (Sandbox Code Playgroud)
  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>
    
    Run Code Online (Sandbox Code Playgroud)

尽管如此,它仍然是必需的,否则,MockMVC由于没有上下文,将无法启动。

  1. controllerTest使用以下注释配置您的类:

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

我应该提到,没有@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();
    }
    
    Run Code Online (Sandbox Code Playgroud)

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

基本上就是这样。