JMockit编写java单元测试

JMockit实例

package test.mock.jmockit;

import static org.junit.Assert.assertEquals;
import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.Injectable;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;
import mockit.Tested;

import org.junit.Test;

public class TestJMockit {

	/**
	 * mock代理dao方法
	 */
	@Test
	public void result(){
		//1. mock对象【mock一个dao并设置其某个方法的期望返回值】
		MockUp mockUp = new MockUp() {
			@Mock
			public int getCount(){//设置dao里面的方法,下面的调用就会调用本方法
				return 70;
			}
		};
		
		//2. 获取mock实例
		Dao dao = mockUp.getMockInstance();
		
		Service service = new Service();
		service.setDao(dao);
		//3. 调用
		String sign = service.getCount();
		System.out.println("测试结果:"+sign);
		assertEquals("良好", sign);
		
		//4. 还原对象,避免测试方法之间互相影响。其实对一个实例来说没什么影响,对静态方法影响较大。旧版本的tearDown()方法是Mockit类的静态方法
		mockUp.tearDown();//dao为null,不可用了
		
//		String sign2 = service.checkCount();
//		System.out.println("====="+sign2);
		
	}
	/**
	 * 测试方法入参直接被mock
	 * @param dao
	 */
	@Test
	public void param(@Mocked final Dao dao){
		
		new Expectations() {
			{
				dao.getCount();
				result = 66;
				times = 1;
			}
		};
		Service service = new Service();
		service.setDao(dao);
		String sign = service.getCount();
		System.out.println("测试结果:"+sign);
	}
	
	@Test
	public void privateMethod() {
		new Expectations(Service.class) {
			{
				Deencapsulation.invoke(Service.class, "hello");//invoke能调用私有方法
//				returns(16);
				result = 16;
//				times = 1;
			}
		};
		
		int age = Service.test();
		System.out.println("测试结果:"+age);
	}
	
//================================
	@Tested		//自动构建,无需new,自动构建和注入实例
	Service serviceAI;
	@Injectable		//自动构建并注入到@Tested实例中,并且自动会被mock
	Dao daoAI;
	/**
	 * 自动注入:dao、service
	 */
	@Test
	public void autoInject(){
		new Expectations() {//设置dao返回结果
			{
				daoAI.getCount();
				result = 89;
			}
		};
		
		String sign = serviceAI.getCount();
		System.out.println("测试结果:"+sign);
		
	}

}

 

package test.mock.jmockit;

public class Service {

	Dao dao;
	public static int test(){
		return hello();
	}
	public int getStudentAge(){
		return getAge();
	}
	private static int hello(){
		int age = 13;
		System.out.println("查询学生年龄为:"+age);
		return age;
	}
	private static int getAge(){
		int age = 13;
		System.out.println("查询学生年龄为:"+age);
		return age;
	}
	/**
	 * 计算学生得分等级
	 * @return
	 */
	public String getCount(){
		int count = dao.getCount();
		
		String sign = "不及格";
		if(count < 60){
			System.out.println("不及格:"+count);
		}else if(count < 90){
			System.out.println("良好:"+count);
			sign = "良好";
		}else{
			System.out.println("优秀:"+count);
			sign = "优秀";
		}
		return sign;
	}

	public Dao getDao() {
		return dao;
	}

	public void setDao(Dao dao) {
		this.dao = dao;
	}
	
}

 

package test.mock.jmockit;

public interface Dao {

	int getCount();
	int getAge();
}

 

 

 

你可能感兴趣的:(单元测试)