Java单元测试之 Spring MVC / Restful

简介: 对于程序员是否有必要编写test case,何时编写依然存在很多争议,各种互斥的方法论(SE/AM/XP/TDD),以及不同的开发文化,但是可以确定是编写单元测试用例有助于提高编程能力。

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);
        }
    }
}
相关文章
|
1天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
2天前
|
负载均衡 Java 开发者
细解微服务架构实践:如何使用Spring Cloud进行Java微服务治理
【4月更文挑战第17天】Spring Cloud是Java微服务治理的首选框架,整合了Eureka(服务发现)、Ribbon(客户端负载均衡)、Hystrix(熔断器)、Zuul(API网关)和Config Server(配置中心)。通过Eureka实现服务注册与发现,Ribbon提供负载均衡,Hystrix实现熔断保护,Zuul作为API网关,Config Server集中管理配置。理解并运用Spring Cloud进行微服务治理是现代Java开发者的关键技能。
|
3天前
|
安全 Java 数据安全/隐私保护
使用Spring Security进行Java身份验证与授权
【4月更文挑战第16天】Spring Security是Java应用的安全框架,提供认证和授权解决方案。通过添加相关依赖到`pom.xml`,然后配置`SecurityConfig`,如设置用户认证信息和URL访问规则,可以实现应用的安全保护。认证流程包括请求拦截、身份验证、响应生成和访问控制。授权则涉及访问决策管理器,如基于角色的投票。Spring Security为开发者构建安全应用提供了全面且灵活的工具,涵盖OAuth2、CSRF保护等功能。
|
4天前
|
安全 Java API
RESTful API设计与实现:Java后台开发指南
【4月更文挑战第15天】本文介绍了如何使用Java开发RESTful API,重点是Spring Boot框架和Spring MVC。遵循无状态、统一接口、资源标识和JSON数据格式的设计原则,通过创建控制器处理HTTP请求,如示例中的用户管理操作。此外,文章还提及数据绑定、验证、异常处理和跨域支持。最后,提出了版本控制、安全性、文档测试以及限流和缓存的最佳实践,以确保API的稳定、安全和高效。
|
4天前
|
Java 大数据 云计算
Spring框架:Java后台开发的核心
【4月更文挑战第15天】Spring框架在Java后台开发中占据核心位置,因其控制反转(IoC)、面向切面编程(AOP)、事务管理等特性提升效率和质量。Spring提供数据访问集成、RESTful Web服务和WebSocket支持。优势包括高效开发、灵活扩展、强大生态圈和广泛应用。应用于企业级应用、微服务架构及云计算大数据场景。掌握Spring对Java开发者至关重要。
|
7天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
21 3
|
7天前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
13 1
|
7天前
|
前端开发 Java Spring
数据之桥:深入Spring MVC中传递数据给视图的实用指南
数据之桥:深入Spring MVC中传递数据给视图的实用指南
24 3
|
7天前
|
Java 应用服务中间件 Maven
使用IDEA搭建SpringMVC环境,Maven导入了依赖,但是运行报错 java.lang.ClassNotFoundException
使用IDEA搭建SpringMVC环境,Maven导入了依赖,但是运行报错 java.lang.ClassNotFoundException
8 1
|
16天前
|
存储 安全 Java
Spring Security应用讲解(Java案列演示)
Spring Security应用讲解(Java案列演示)