新人上路-搭建项目-springweb-controller测试
maven和gradle配置
-
测试controller最基本的依赖
-
maven
<!-- main framework begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- main framework end --> <!-- web begin --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- web end --> <!-- test begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${mockito.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- test end -->
gradle
dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-devtools") testCompile("org.springframework.boot:spring-boot-starter-test") testCompile("org.mockito:mockito-core:$mockitoVersion") }
-
springmvc javaconfig配置
-
WebAppInitializer
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class<?>[] getRootConfigClasses() { return new Class<?>[]{ RootConfig.class }; } protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{ WebConfig.class }; } protected String[] getServletMappings() { return new String[]{"/"}; } /** 添加字符集过滤器 **/ @Override public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter("utf-8", true)) .addMappingForUrlPatterns(null, false, "/*"); } }
-
WebConfig
@Configuration @EnableWebMvc @ComponentScan("com.seal_de.controller") public class WebConfig extends WebMvcConfigurerAdapter { /** 解析json返回数据 **/ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList(converter.getSupportedMediaTypes()); mediaTypes.addAll(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.TEXT_XML)); converter.setSupportedMediaTypes(mediaTypes); ObjectMapper objectMapper = converter.getObjectMapper(); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); converters.add(converter); } /** 静态资源不做处理 **/ @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
-
RootConfig
@Configuration @ComponentScan(basePackages = {"com.seal_de"}, excludeFilters={@ComponentScan.Filter(type= FilterType.ANNOTATION, value= EnableWebMvc.class)}) public class RootConfig { }
springboot javaconfig
-
WebConfig
@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } /**解析json返回数据**/ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList(converter.getSupportedMediaTypes()); converter.setSupportedMediaTypes(mediaTypes); mediaTypes.addAll(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.TEXT_XML)); ObjectMapper objectMapper = converter.getObjectMapper(); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); converters.add(converter); } }
测试controller
-
controller
@RestController public class HomeController { @RequestMapping("/") public String home() { return "home"; } @RequestMapping("/cn") public String cn() { return "中文测试"; } @RequestMapping("/object") public Book object() { return new Book(10, "springmvc-javaconfig踩坑记录", new Date()); } private class Book { private Integer id; private String name; private Date pubDate; public Book(Integer id, String name, Date pubDate) { this.id = id; this.name = name; this.pubDate = pubDate; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getPubDate() { return pubDate; } public void setPubDate(Date pubDate) { this.pubDate = pubDate; } } }
-
controller测试
import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; /** * Created by sealde on 5/27/17. */ public class HomeControllerTest { private MockMvc mockMvc; @InjectMocks private HomeController controller; @Before public void setUp() { MockitoAnnotations.initMocks(this); this.mockMvc = standaloneSetup(controller).build(); } @Test public void testHome() throws Exception { mockMvc.perform(get("/")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string("home")); } @Test public void testCn() throws Exception { mockMvc.perform(get("/cn") .accept(MediaType.APPLICATION_JSON_UTF8)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string("中文测试")); } @Test public void testObject() throws Exception { mockMvc.perform(get("/object") .accept(MediaType.APPLICATION_JSON_UTF8)) .andDo(print()) .andExpect(status().isOk()); } }
尚未解决
单元测试不知道怎么使用 WebConfig 的配置
最后
代码(springmvc dev1分支): http://git.oschina.net/sealde...
代码(springboot dev1分支): https://git.oschina.net/seald...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。