测试方法junit

在方法大量的情况下,用main函数一个个测试的话需要不断地加注释符取消方法的运行,很麻烦!!

采用junit的测试方法非常简便。

首先morenb创建Person.java

package study;

public class Person {
	public void eat(){
		System.out.println("eat!!!");
	}
	public void run(){
		System.out.println("run!!!");
	}
}

 在测试包junit.test中创建测试方法PersonTest    PersonTest.java

package junit.test;

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

public class PersonTest {
	
	@Before
	public void setUp() throws Exception{
		System.out.println("所有的测试方法运行之前运行!!");
	}
	
	@Test
	public void testEat() {
		study.Person p = new study.Person();	
		p.eat();
	}
	
	@Test
	public void testRun() {
		study.Person p = new study.Person();
		p.run();
	}
	
	@After
	public void tearDown() throws Exception{
		System.out.println("所有的测试方法运行之后运行!!");
	}
}

运行结果:

所有的测试方法运行之前运行!!
eat!!!
所有的测试方法运行之后运行!!
所有的测试方法运行之前运行!!
run!!!
所有的测试方法运行之后运行!!
 

这个junit测试的方便之处在于写好了测试方法之后可以在右边的outline里单独测试各个方法!

例如单独测试Eat方法:右键testEat():void --> Run As

测试结果:

所有的测试方法运行之前运行!!
eat!!!
所有的测试方法运行之后运行!!

技巧:

红框上面两个BeforeClass和AfterClass主要是在方法运行之前运行和方法运行之后运行!常用于加载时初始化资源。

package junit.test;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class PersonTest3 {

	@BeforeAll
	static void setUpBeforeClass() throws Exception {
		System.out.println("Before");
	}

	@Test
	public void testEat() {
		study.Person p = new study.Person();	
		p.eat();
	}
	
	@Test
	public void testRun() {
		study.Person p = new study.Person();
		p.run();
	}

	@AfterAll
	static void tearDownAfterClass() throws Exception {
		System.out.println("After");
	}

}

运行结果:

Before
eat!!!
run!!!
After
 

猜你喜欢

转载自blog.csdn.net/qq_40956679/article/details/81067423
今日推荐