Junit

原创 2016年05月31日 20:51:43

Spring测试

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.bestcxx.stu.springmvc.model.UserModel;
import com.bestcxx.stu.springmvc.service.UserModelService;

@DirtiesContext
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/springmvc-servlet.xml"})
//@TransactionConfiguration(transactionManager = "defaultTransactionManager",defaultRollback=false)//事务管理  
@Rollback(true)
public class UserModelServiceImplTest  extends AbstractTransactionalJUnit4SpringContextTests{

Spring Boot 测试

<dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-test</artifactId>  
            <scope>test</scope>  
        </dependency>  

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;

import cn.acsm.paddy.manage.Application;
import cn.acsm.paddy.manage.applyrecord.entity.ApplyRecord;
import cn.acsm.paddy.manage.applyrecord.service.ApplyRecordService;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Rollback(true)
public class ApplyRecordServiceTest extends AbstractTransactionalJUnit4SpringContextTests{

TestCase-try-Catch

@Test
	public void test(){
		int id=10000;
		EnterpriseInfo e=eService.getById(id);
		
		e.setUpdateUser(10000);//最后更新用户
		try {
			eService.update(e);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			TestCase.fail("保存失败");
		}
		
	}


Mock

validate 的 maven依赖

<!-- validation 校验 开始 -->  
    <dependency>  
        <groupId>org.hibernate</groupId>  
        <artifactId>hibernate-validator</artifactId>  
        <version>5.4.1.Final</version>  
    </dependency>  
    <dependency>  
        <groupId>javax.el</groupId>  
        <artifactId>javax.el-api</artifactId>  
        <version>2.2.4</version>  
    </dependency>  
    <dependency>  
        <groupId>org.glassfish.web</groupId>  
        <artifactId>javax.el</artifactId>  
        <version>2.2.4</version>  
    </dependency>  
    <!-- validation 校验 结束 -->      

Mock 测试举例

package com.bestcxx.stu.springmvc.controller;  
  
import org.junit.Before;  
import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
import org.springframework.test.annotation.DirtiesContext;  
import org.springframework.test.annotation.Rollback;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;  
import org.springframework.test.context.junit4.SpringRunner;  
import org.springframework.test.context.web.WebAppConfiguration;  
import org.springframework.test.web.servlet.MockMvc;  
import org.springframework.test.web.servlet.MvcResult;  
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;  
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;  
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;  
import org.springframework.test.web.servlet.setup.MockMvcBuilders;  
import org.springframework.web.context.WebApplicationContext;  
  
  
@DirtiesContext  
@RunWith(SpringRunner.class) //@RunWith(SpringJUnit4ClassRunner.class)  也是可以的  
@WebAppConfiguration   //单元测试的时候真实的开启一个web服务      
@ContextConfiguration(locations={"classpath:spring/springmvc-servlet.xml"})   
//@TransactionConfiguration(transactionManager = "defaultTransactionManager",defaultRollback=false)//事务管理      
@Rollback(true)    
public class ParameterControllerTest extends AbstractTransactionalJUnit4SpringContextTests{    
    @Autowired    
    private WebApplicationContext wac;    
    private MockMvc mockMvc;    
    @Before    
    public void setup() {    
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();   //构造MockMvc    
    }    
        
    @Test    
    public void testModel() throws Exception{    
         MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/parameterController/model") // 请求的url,请求的方法是post    
                 .contentType(MediaType.APPLICATION_JSON) // 数据的格式    
                 .param("name"," " ) // 增加参数  
         ).andExpect(MockMvcResultMatchers.status().isOk()) // 返回的状态是200  
                 .andDo(MockMvcResultHandlers.print()) // 打印出请求和相应的内容    
                 .andReturn(); // 将相应的数据转换为字符串    
         System.out.println("--------返回的json = " + mvcResult.getResponse().getContentAsString());    
    }    
}   

Spring boot 举例


import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.io.UnsupportedEncodingException;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import junit.framework.TestCase;


@RunWith(SpringRunner.class)  
@SpringBootTest
@WebAppConfiguration   
@Rollback(true) //单元测试配置数据库默认会事务会退  此时强制事务提交  
public class ApplyRecordControllerTest extends AbstractTransactionalJUnit4SpringContextTests{
	
	private MockMvc mockMvc;  
    @Autowired   
    protected WebApplicationContext wac;  
  
    // 该方法在每个方法执行之前都会执行一遍  
    @Before  
    public void setUp() throws Exception {  
        //mockMvc = MockMvcBuilders.standaloneSetup(new NameController()).build();  
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象  
    }  
    
    
    @Test  
    public void test1() throws UnsupportedEncodingException, Exception {  
        String responseString = mockMvc.perform(post("/a/b") // 请求的url,请求的方法是post  
                .contentType(MediaType.APPLICATION_JSON) // 数据的格式  
                .param("a","111" ) // 参数
                .param("b", "222")//参数
        ).andExpect(status().isOk()) // 返回的状态是200
                .andDo(print()) // 打印出请求和相应的内容  
                .andReturn().getResponse().getContentAsString(); // 将相应的数据转换为字符串  
        System.out.println("--------返回的json = " + responseString);  
    }
    
    @Test  
    public void test2() throws UnsupportedEncodingException, Exception {  
        String responseString = mockMvc.perform(post("/c/d") // 请求的url,请求的方法是post  
                .contentType(MediaType.APPLICATION_JSON) // 数据的格式  
                .param("a","111" ) // 参数
                .param("c","222" ) // 参数
              
        ).andExpect(status().isOk()) // 返回的状态是200
                .andDo(print()) // 打印出请求和相应的内容  
                .andReturn().getResponse().getContentAsString(); // 将相应的数据转换为字符串  
        System.out.println("--------返回的json = " + responseString);  
    }
    
    @Test
    public void test3() throws UnsupportedEncodingException, Exception {
    	MvcResult mvcResult = mockMvc.perform(get("/a/1000") // 请求的url,请求的方法是post  
                 .contentType(MediaType.APPLICATION_JSON) // 数据的格式 
         ).andExpect(status().isOk())// 返回的状态是200
                 //.andDo(print()) // 打印出请求和相应的内容  
                 .andReturn()
                 ; // 将相应的数据转换为字符串  
         TestCase.assertEquals("/a/b/c", mvcResult.getModelAndView().getViewName());//返回页面是否符合预期
    }

}





版权声明:本文为博主原创文章,欢迎转载,转载请声明出处 http://blog.csdn.net/bestcxx。

相关文章推荐

Junit jar 包

  • 2017-08-22 15:29
  • 227KB
  • 下载

Junit 单元测试在 intelliJ IDEA 中的应用

Junit在intelliJ IDEA

junit4.0.zip

  • 2017-06-07 14:34
  • 216KB
  • 下载

【随记】一次测试多个JUnit单元测试类(方法)

如何使用junit做单元测试? 答案很简单:搭好环境写好测试类,运行就可以了!但如果我有很多个测试类(方法),如何做到一次运行多个测试类呢?首先创建个待测试的beanpackage test; pu...

junit4.11+hamcrest-all-1.3.jar

  • 2017-09-26 08:57
  • 480KB
  • 下载

junit 单元测试 jar包

  • 2017-08-20 09:36
  • 232KB
  • 下载

使用RunWith注解改变JUnit的默认执行类,并实现自已的Listener

使用RunWith注解改变JUnit的默认执行类,并实现自已的Listener在平时的单元测试,如果不使用RunWith注解,那么JUnit将会采用默认的执行类Suite执行,如下类: ...
  • ynwso
  • ynwso
  • 2013-10-12 11:15
  • 849
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)