【问题标题】:Use MockMVC outside SpringBoot application在 Spring Boot 应用程序之外使用 MockMVC
【发布时间】:2017-08-26 00:06:29
【问题描述】:

我有一个使用 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();

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

【问题讨论】:

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


    【解决方案1】:

    事实证明,这是绝对可以做到的。启动它只需要一些配置。

    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 将不会启动,因为没有上下文。

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

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

    我应该提到,没有@ContextConfiguration MockMVC 将无法工作。

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

      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();
      }
      

    据我了解,setHandlerExceptionResolversmockMVC 设置的关键部分。

    基本上就是这样。

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 1970-01-01
      • 2017-10-01
      • 2019-05-18
      • 2015-01-01
      • 1970-01-01
      • 2015-05-20
      • 2021-12-16
      • 2019-08-05
      相关资源
      最近更新 更多