開發與維運

Java單元測試之 Spring MVC / Restful

spring-test同樣提供內置MVC容器,可以對Spring MVC進行單元測試

SpringMVCDemoTest.java

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
 
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class SpringMVCDemoTest {
    ...
}

下面是一個簡單的Spring MVC測試示例,Spring Controller和Spring Restful,區別就在於 @Controller 和 @RestController

application-controller.xml

<context:component-scan base-package="com.faw_qm.cloud.platform.*.controller"/>
 
<mvc:default-servlet-handler />
 
<mvc:annotation-driven>
   <mvc:message-converters>
      <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
         <property name="supportedMediaTypes">
            <list>
               <value>application/json;charset=UTF-8</value>
            </list>
         </property>
      </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

DemoController.java

@Controller
@RequestMapping("demo")
public class DemoController {
 
    @RequestMapping("test")
    public @ResponseBody String method(@RequestBody String name) {
 
        return "This is a spring mvc test method.";
    }
}

SpringMVCDemoTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath*:/applicationContext-controller.xml"})
public class SpringMVCDemoTest {
 
    @Autowired
    private WebApplicationContext wac;
 
    private MockMvc mockMvc;
 
    @Before
    public void setup() {
 
        this.mockMvc = webAppContextSetup(this.wac).build();
    }
 
    @Test
    public void method() throws Exception {
 
        JSONObject json = new JSONObject();
 
        json.put("name", "test");
 
        mockMvc.perform((post("/demo/test")
                .characterEncoding("UTF-8")
                .content(json.toJSONString())
                .contentType(MediaType.APPLICATION_JSON)))
                .andExpect(status().isOk())
                .andDo(print());
    }
}

基於註解方式的測試示例(過多的配置文件在單元測試時有時顯得很繁瑣)

DemoController.java

@RestController
@RequestMapping("demo")
public class DemoController {
 
    @PostMapping(path = "/test", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody String method(@RequestBody String name) {
 
        return "This is a spring mvc test method.";
    }
}

SpringMVCDemoTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class SpringMVCDemoTest {
 
    @Autowired
    private WebApplicationContext wac;
 
    private MockMvc mockMvc;
 
    @Before
    public void setup() {
 
        this.mockMvc = webAppContextSetup(this.wac)
                .addFilter(new CharacterEncodingFilter("UTF-8", true))
                .build();
    }
 
    @Test
    public void method() throws Exception {
 
        JSONObject json = new JSONObject();
 
        json.put("name", "test");
 
        mockMvc.perform((post("/demo/test")
                .characterEncoding("UTF-8")
                .content(json.toJSONString())
                .contentType(MediaType.APPLICATION_JSON)))
                .andExpect(status().isOk())
                .andDo(print());
    }
 
 
    @ComponentScan(basePackages = "com.faw_qm.cloud.platform.*.controller")
    @Configuration
    @EnableWebMvc
    public static class WebMvcConfig extends WebMvcConfigurerAdapter {
 
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            converters.add(converter);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *