First, the installation of Junitt
Right-click on project name, point properties---->>> Standalone Select Java Build path----->>> Select library (L)----->>> Add Library----->>> Select JUnit----->>> Select version
Ii. Use of JUnit
JUNIT4 using annotations in Java5 (annotation), here are a few annotation commonly used by JUNIT4:
@Before: Initialization method Every test method is executed once (Note theBeforeclass difference, the latter being performed once for all methods)
@After: Release resource Afterclass difference, which is performed once for all methods)
@Test: Test method, where you can test for expected exceptions and time-outs
@Test (expected=arithmeticexception.class) Check if the method being tested throws ArithmeticException exception
@Ignore: ignored test method
@BeforeClass: All tests, executed only once, and
@AfterClass: for a JUNIT4 unit test case Execution order is:
@AfterClass, @After, @Test, @Before, @BeforeClass,
@After, @Test, @Before
1. Use of @before and @after
Public class Person { publicvoid run () { System.out.println ("Run"); } Public void Eat () { System.out.println ("eat");} }
ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.junit.Test; Public classTest1 {PrivatePerson p; @Before//The method that uses the metadata is executed one time before each test method executes. Public voidbefore () {p=NewPerson (); System.out.println ("Before"); } @Test Public voidTestRun ()//test Method{p.run (); } @Test Public voidTesteat ()//test Method{p.eat (); } @After//The method that uses the metadata is executed once after each test method executes. Public voidAfter () {p=NULL; System.out.println ("After"); } }
Program execution Results:
Before
Eat
After
Before
Run
After
2. Use of @beforeClass and @afterClass
ImportOrg.junit.AfterClass;ImportOrg.junit.BeforeClass;Importorg.junit.Test; Public classtest2{@BeforeClass//for all tests, execute only once and must be static void Public Static voidBeforeclass () {System.out.println ("Beforeclass"); } @Test Public voidTestRun ()//test Method{person P=NewPerson (); P.run (); } @Test Public voidTesteat ()//test Method{person P=NewPerson (); P.eat (); } @AfterClass//for all tests, execute only once and must be static void Public Static voidAfterclass () {System.out.println ("Afterclass"); } }
Execution Result:
Beforeclass
Eat
Run
Afterclass
JUnit Test Framework