`
chinrui
  • 浏览: 94254 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

JUnit入门

阅读更多
Junit笔记

1、 单元测试
package edu.hpu.junit;

public class T {
	public int plus(int x , int y) {
		return x + y;
	}
}

//测试用
package edu.hpu.junit.test;

//静态引入,引入相应的方法,而不用再写类名
import static org.junit.Assert.*;

import org.junit.Test;

import edu.hpu.junit.T;

public class TTest {

	@Test
	public void testPlus() {
		int z = new T().plus(3, 5);
		assertEquals(8, z);
	}
}

2、 Error与Failure
Error是程序出错,Failure是测试失败
3、 测试方法是否抛出相应的异常
@Test(expected=java.lang.ArithmeticException.class)
public void testDivide() {
	int z = new T().divide(8, 0);
}

4、 测试程序的执行速度
@Test(expected=java.lang.ArithmeticException.class, timeout=100)
public void testDivide() {
	int z = new T().divide(8, 0);
}

5、 @before与@after
package edu.hpu.junit.test;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import edu.hpu.junit.T;

public class TTest {
	
	@Before
	public void before() {
		System.out.println("before");
	}

	@Test
	public void testPlus() {
		int z = new T().plus(3, 5);
		assertEquals(8, z);
	}
	
	@Test(expected=java.lang.ArithmeticException.class, timeout=100)
	public void testDivide() {
		int z = new T().divide(8, 0);
	}
	
	@After
	public void after() {
		System.out.println("after");
	}

}

运行结果:
before
after
before
after
表明每当测试一个方法前运行一下用@before标识的方法,结束时运行一下用@after标识的方法
6、 @BeforClass和@AfterClass
package edu.hpu.junit.test;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import edu.hpu.junit.T;

public class TTest {
	
	@BeforeClass
	public static void beforeClass() {
		System.out.println("beforeClass");
	}
	
	@AfterClass
	public static void afterClass() {
		System.out.println("afterClass");
	}
	
	@Before
	public void before() {
		System.out.println("before");
	}

	@Test(expected=java.lang.ArithmeticException.class, timeout=100)
	public void testDivide() {
		int z = new T().divide(8, 0);
	}
	
	@After
	public void after() {
		System.out.println("after");
	}

}

运行结果:
beforeClass
before
after
afterClass
表明当Class未初始化前执行BeforeClass标识的方法,程序运行完以后执行AfterClass方法
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics