seminar junit( 13520408--13520449--13520495 )

36
SEMINAR JAVA – JUNIT Vũ Văn Mạnh 13520495 Lê Khánh Linh 13520449 Đỗ Đức Khôi 13520408 GVBM : Thầy NGUYỄN TRÁC THỨC

Upload: hotkutepro

Post on 20-Sep-2015

224 views

Category:

Documents


4 download

DESCRIPTION

JUNIT in java

TRANSCRIPT

PowerPoint Presentation

SEMINAR JAVA JUNIT

GVBM : Thy NGUYN TRC THC JUnit ??? Cc ngn ng lp trnh nh nh ASP, C++, C, Delphi, Perl, PHP, REBOL, Python, u c b h tr Unit Test ring ca n. JUnit l mt framework c dng cho Unit Test trong Java.

y cng l mt trong nhng test framework ph bin nht cho Java ( bn cnh TestNG ). Vic thc hin Unit Test trong Java l bt buc hu ht cc d n pht trin phn mm m bo cht lng sn phm.

lp trnh vin s dng cng c Unit Testing song hnh vi qu trnh pht trin ng dng nhm nhanh chng pht hin nhng li logic khi vit m.

Nu khng c cc cng c Unit Testing, khi bn vit d ch mt hm trong chng trnh thi, th bn s lm mt vic lp i lp li mt cch nhm chn l: mi ln chnh sa m lnh u phi cho gi tr u vo ri chy on code mnh va vit xong v nhn xem kt qu u ra c ng hay khng.Khi qut JUnit Unit testing l cng c test n thc th ( class hoc method )Unit testing v cng cn thit i vi hu ht cc cng ty phn mm l minh chng cht lng sn phm cho i tc ca hUnit testing chia lm 2 hng

Manual testing ( th cng ) >>Thc hin test case bng cch th cng m khng nh s h tr t cng c test .

Tn nhn lc: Nhiu test case cn c thc hin th cng cn nhiu tester

tin cy thp : do s nhm ln , sai st ca con ngi

Non-programmable: Cc dng test khng qu phc tp nn t khi d c bug n

Automated testing ( t ng )

Cng c test t ng thc hin rt nhanh chng gp nhiu ln Tn t nhn lc v mi cng c c hiu sut bng nhiu tester . tin cy cao v cng c t ng thc hin rt chnh xc mi ln test Programmable: Cc tester c th lp trnh cc dng test phc tp v chng c th tm ra nhng l hng n / bug n

Features ( tnh nng )

JUnit l mt m ngun m Java th nghim khung c s dng vit v chy th nghim lp li. Cung cp Assertion ( xc thc ) kim tra kt qu mong i Cung cp Annotation ( ch gii ) xc nh cc phng thc test Cung cp Test runner thc hin test JUnit test c th t chc thnh b test ( test suite ) cha nhiu php th ( test case ) hoc c th cha cc test suite khc JUnit xut qu trnh test qua thanh trng thi :

Pass

FailCh gii Ch gii trong JUnit cung cp cho chng ta thng tin v cc phng thc test , nh phng thc no s chy trc & sau cc phng thc test , phng thc no hay lp no s b b qua trong qu trnh thc thi . @TestThng bo JUnit rng phng thc public void di y hot ng nh test case

@BeforeCc phng thc km ch gii ny s c thc thi trc mi phng thc test

@AfterCh thch rng phng thc public void km @After s khin cc phng thc c thc thi sau phng thc Test @BeforeClassCh thch phng thc public static void c thc thi trc ht bt k phng thc test no trong class

@AfterClassThng dng khi thc hin hot ng dn dp , ty xa ( sau khi chy xong tt c test @IgnoreCh thch rng test s c b qua

JUnit APIGi quan trng nht trong JUnit l junit.framework bao hm tt c cc lp c bn

Lp AssertPUBLIC CLASS ASSERT EXTENDS JAVA.LANG.OBJECTBao gm cc phng thc assertXXX() :

Void assertEquals(boolean expected , boolean actual) : So snh 2 gi tr kim tra bng nhau. Test s c chp nhn nu cc gi tr bng nhauVoid assertFalse(boolean condition) : nh gi biu thc lun l. Test s c chp nhn nu biu thc saiVoid assertNotNull(Object object) : So snh tham chiu ca mt i tng vi null. Test s c chp nhn nu tham chiu i tng khc nullVoid assertNull(Object object) So snh tham chiu ca mt i tng vi gi tr null. Test s c chp nhn nu tham chiu l nullVoid assertTrue(boolean condition) nh gi mt biu thc lun l. Test s c chp nhn nu biu thc ngVoid fail() : Phng thc ny lm cho test hin hnh tht bi, phng thc ny thng c s dng khi x l cc bit l@Testpublic void testAssertions() {//test dataString str1 = new String ("abc");String str2 = new String ("abc");String str3 = null;String str4 = "abc";String str5 = "abc";int val1 = 5;int val2 = 6;String[] expectedArray = {abc", def", bbb"};String[] resultArray = {abc, def", bbb"};//Check that two objects are equalassertEquals(str1, str2);//Check that a condition is trueassertTrue (val1 < val2);//Check that a condition is falseassertFalse(val1 > val2);//Check that an object isn't nullassertNotNull(str1);//Check that an object is nullassertNull(str3);//Check if two object references point to the same objectassertSame(str4,str5);//Check if two object references not point to the same objectassertNotSame(str1,str3);//Check whether two arrays are equal to each other.assertArrayEquals(expectedArray, resultArray);}

To TestRunner chy test case ( test assertion ) import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;public class TestRunner2 {public static void main(String[] args) {Result result =JUnitCore.runClasses(TestAssertions.class);for (Failure failure : result.getFailures()) {System.out.println(failure.toString());}System.out.println(result.wasSuccessful());}}

Lp Test CasePUBLIC ABSTRACT CLASS TestCase extends Assert implement Test int countTestCases()>> m s php th c gi bi run(TestResult result)TestResult createResult()>> To i tng TestResult mc nh String getName()>> Gets the name of a TestCase. TestResult run()Phng thc chy test v thu thp kt qu vi i tng TestResultvoid run(TestResult result)Chy test case v xut kt qu trong TestResult void setName(String name)Sets the name of a TestCase. void setUp()VD nh thc hin m kt ni void tearDown()VD nh hy kt ni String toString()Tr v chui i din cho php th .

setUp() v tearDown()Hai phng thc ny l mt phn ca lp junit.framework.TestCase. Khi s dng hai phng thc ny s gip chng ta trnh c vic trng m khi nhiu test cng chia s nhau phn khi to v dn dp cc bin.

Sau khi to xong tt c cc i tng test case, JUnit tun theo cc bc sau cho mi phng thc test:

Gi phng thc setUp() ca test case Gi phng thc th Gi phng thc tearDown() ca test case

Qu trnh ny c lp li i vi mi phng thc th trong Test Case.Thng thng chng ta c th b qua phng thc tearDown() v mi phng thc th ring khng phi l nhng tin trnh chy tn nhiu thi gian v cc i tng c thu dn khi my o Java (JVM) thot.

Phng thc tearDown() c th c s dng khi test ca bn thc hin nhng thao tc nh m kt ni n c s d liu hay s dng cc loi ti nguyn khc ca h thng v bn cn phi dn dp ngay lp tc.

import junit.framework.TestCase;import org.junit.Before;import org.junit.Test;public class TestJunit2 extends TestCase {protected double fValue1;protected double fValue2;@Beforepublic void setUp() {fValue1= 2.0;fValue2= 3.0;}@Testpublic void testAdd() {//Dem so phep thuSystem.out.println(So luong Test Case = "+ this.countTestCases());

//test getNameString name= this.getName();System.out.println("Test Case Name = "+ name);

//test setName 12Lp TestResultPublic class TestResult extends void addError(Test test, Throwable t)Thm bo li trong danh sch li void endTest(Test test)Thng bo test hon tt int errorCount()Tr v s li pht hin c

int failureCount()Tr v s kt qu sai pht hin c void run(TestCase test)Chy TestCase. int int runCount()Tr v s lng test ang chyvoid startTest(Test test)Thng bo test chun b chy void stop()nh du vic chy test nn ngng .

import org.junit.Test;import junit.framework.AssertionFailedError;import junit.framework.TestResult;public class TestJunit3 extends TestResult {// add the errorpublic synchronized void addError(Test test, Throwable t) {super.addError((junit.framework.Test) test, t);}// add the failurepublic synchronized void addFailure(Test test, AssertionFailedError t) {super.addFailure((junit.framework.Test) test, t);}@Testpublic void testAdd() {// add any test}// Marks that the test run should stop.public synchronized void stop() {//stop the test here}}To TestRunner chy Test case ( vd : TestRunner3 ) import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;public class TestRunner3 {public static void main(String[] args) {

Result result = JUnitCore.runClasses(TestJunit3.class);for (Failure failure : result.getFailures()) {System.out.println(failure.toString());}System.out.println(result.wasSuccessful());}}

Test Suite Chng ta khng nn kt hp nhiu php th khng lin quan n nhau vo trong cng mt phng thc testXXX(). Mt phng thc th c th cha nhiu hn mt phng thc assertXXX(). Khi chng ta cn kim tra mt dy cc iu kin v mt php th tht bi s khin cc test theo sau tht bi , khi chng ta c th kt hp nhiu phng thc assertXXX() vo trong mt phng thc th.

Thng thng th JUnit s t ng to ra cc Test Suite ng vi mi Test Case. Tuy nhin, chng ta cng c th t to ra cc Test Suite ring ca mnh bng cch t chc cc Test Case vo Test Suite, c h tr bi lp junit.framework.TestSuite. Test Suite cho php kt hp cc Test Case to ra mt php th tng qut.public class TestXXX extends TestCase{public static Test suite() {return new TestSuite(TestXXX.class);}}

Bng cch truyn i tng TestXXX.class vo hm khi to TestSuite, chng ta ang thng bo cho JUnit bit xc nh tt c cc phng thc TestXXX () ca lp TestXXX v thm chng vo suite. Chng ta c th kt hp nhiu suite vo cc suite khc. V d nh sau:

public static Test suite() {TestSuite suite = new TestSuite(TestXXX.class);suite.addTest(new TestSuite(TestYYY.class));return suite;} s dng Junit Test , ta click chut phi vo Java Project to chn Properties > Java Build Path > Library> Add Library > Junit> Ty chn Junit 3 hoc 4> FinishTa to mt class nh sau: Money.java

package Money;public class Money {private double amount;private String currency;public Money(double amount, String currency) {this.amount = amount;this.currency = currency;}public boolean equals (Money a){if (this.amount==a.amount&& this.currency.equals(a.currency))return true;else return false; }public Money AddMoney (Money a, Money b){if (a.equals(b)){Money c= new Money(0,a.currency);c.amount=a.amount+b.amount;return c; }else return null;}

Sau click chut phi vo class chn New > Junit Test Case > chng trnh s t t tn theo quy c chun nh sau:

Test Case Class: c t tn [classname]Test.java, vi classname l tn ca lp c test. Test Case Method: c t tn test[methodname], vi methodname l tn ca phng thc c test. Test Suite: mc nh tn cho Eclipse l AllTests.java

Ta ch cn tip tc chn Next > chn phng thc cn test > Finish.

package Money;import static org.junit.Assert.*;import org.junit.Test;public class MoneyTest {@Testpublic void testEqualsMoney() {Money m1 = new Money(200, VND);Money m2 = new Money(1000, VND);assertTrue(m1.equals(new Money(200, VND)));assertFalse(m1.equals(m2));}@Testpublic void testAddMoney() {Money m1 = new Money(200, VND);Money m2 = new Money(1000, VND);Money result = m1.AddMoney(m1,m2);Money expected = new Money(1200, VND);assertTrue(Result,expected.equals(result));}}Test lp phi to mt lp con tha k t lp junit.framework.TestCase. Mi unit test c i din bi mt phng thc testXXX() bn trong lp con ca lp TestCase

Ta c mt lp Person nh sau:

public class Person {private String firstName;private String lastName;

public Person(String firstName, String lastName) {if (firstName == null && lastName == null) {throw new IllegalArgumentException(Both names cannot be null);}this.firstName = firstName;this.lastName = lastName;}

public String getFullName() {String first = (this.firstName != null) ? this.firstName : ?;String last = (this.lastName != null) ? this.lastName : ?;

return first + last;}

public String getFirstName() {return this.firstName;}

public String getLastName() {return this.lastName;}}vit mt test case n gin test mt s phng thc ca lp trnimport junit.framework.TestCase;

public class TestPerson extends TestCase {public TestPerson(String name) {super(name);}

/*** Xac nhan rang name duoc the hien dung dinh dang*/public void testGetFullName() {Person p = new Person(Aidan, Burke);assertEquals(Aidan Burke, p.getFullName());}

/*** Xac nhan rang nulls da duoc xu ly chinh xac*/public void testNullsInName() {Person p = new Person(null, Burke);assertEquals(? Burke, p.getFullName());

p = new Person(Tanner, null);assertEquals(Tanner ?, p.getFullName());}}

bin dch TestPerson, chng ta phi khai bo gi th vin junit trong bin ng mi trng classpathset classpath=%classpath%;.;junit.jarjavac TestPerson chy mt JUnit TestCase, ta c 2 cch

Chy vi mi trng text, cc bn g lnhjava junit.textui.TestRunner TestPerson

Sau khi chy s c kt qu

Chy vi mi trng hajava junit.swingui.TestRunner TestPerson

Chng ta c th chy trc tip cc TestCase m khng mun kch hot mt trong cc test runner ca JUnit. Chng ta s thm phng thc main() vo test case. VD : public class TestGame extends TestCase {public static void main(String []args) {junit.textui.TestRunner.run(new TestSuite(TestGame.class))}}

vit mt on test sau y:public void testGame() throws BadGameException{Game game = new Game();Ship fighter = game.createFighter(001);assertEquals(Fighter did not have the correct identifier, 001, this.fighter.getId());

Ship fighter2 = this.game.createFighter(001);assertSame(createFighter with same id should return same object, fighter, fighter2);

assertTrue(A new game should not be started yet, !this.game.isPlaying());}

y l mt thit k khng tt v mi phng thc assertXXX() ang kim tra phn khng lin quan ca chc nng. Nu phng thc assertEquals tht bi, phn cn li ca test s khng c thi hnh. Khi xy ra iu ny th chng ta s khng bit cc test khc c ng chc nng hay khngT chc cc test vo cc test suiteNu khng thy phng thc trn, JUnit s s dng k thut reflection t ng xc nh tt c cc phng thc testXXX() trong test case ca bn, ri thm chng vo mt test suite. Sau n s chy tt c cc test trong suite ny. Bn c th to ra bn sao hnh vi ca phng thc suite() mc nh nh sau

public class TestGame extends TestCase{public static Test suite() {return new TestSuite(TestGame.class);}}

Bng cch truyn i tng TestGame.class vo construtor TestSuite, bn ang thng bo cho JUnit bit xc nh tt c cc phng thc testXXX() trong lp v thm chng vo suite. on m trn khng lm khc g so vi vic JUnit t ng lm, tuy nhin bn c th thm cc test c nhn ch chy cc test nht nh no hay l iu khin th t thc thi

import junit.framework.*;

public class TestGame extends TestCase {private Game game;private Ship fighter;

public TestGame(String name) {super(name);}public static Test suite() {TestSuite suite = new TestSuite();suite.addTest(new TestGame(testCreateFighter));suite.addTest(new TestGame(testSameFighters));return suite;}}

c th kt hp nhiu suite vo cc suite khcpublic static Test suite() {TestSuite suite = new TestSuite(TestGame.class);suite.addTest(new TestSuite(TestPerson.class));return suite;}

Lp li test ta mun chy mt test no lp i lp li nhiu ln o hiu sut hay phn tch cc vn trc trc. JUnit cung cp cho chng ta lp junit.extension.RepeatedTest lm c iu ny.

public static Test suite() {//Chy ton b test suite 10 lnreturn new RepeatedTest(new TestSuite(TestGame.class), 10);}

Tham s u tin ca RepeatedTest l mt Test cn chy, tham s th 2 l s ln lp li. V TestSuite ci t interface Test nn chng ta c th lp li ton b test nh trn. Tip theo l v d m t cch xy dng mt test suite m trong cc test khc nhau c lp i lp li khc nhau:

public static Test suite() {TestSuite suite = new TestSuite();//Lp li testCreateFighter 100 lnsuite.addTest(new RepeatedTest(new TestGame(testCreateFighter), 100));//Chy testSameFighters 1 lnsuite.addTest(new TestGame(testSameFighters));//Lp li testGameInitialState 20 lnsuite.addTest(new RepeatedTest(new TestGame(testGameInitialState), 20);return suite;}

JUnit tin ch m rnga) Cactus

Cactus l mt framework unit testing ngun m dng test cho cc on m pha bn server ca Java. c bit l Cactus cho php bn test Servlet, JSP, v Servlet filter. Cactus tha k t JUnit cung cp 3 lp con ca lp junit.framework.TestCase l cc lp:

org.apache.cactus.ServletTestCase org.apache.cactus.JspTestCase org.apache.cactus.FilterTestCase

Mi test case ca Cactus cung cp 1 chc nng c bit. Cactus test thc thi trn c client v server. Khi s dng Cactus bn ch cn to mt lp tha k t 1 trong 3 lp trn. Sau Cactus s to ra v chy 2 th hin ca test case. Mt chy trn JVM pha client, ci cn li chy bn trong JVM ca mi trng chy servlet (servlet container) pha server. Bn client pha client cho php HTTP headers v cc tham s HTTP c thm vo cc yu cu i ra. Bn pha server gi thc thi cc phng thc bn trong servlet ca bn thc hin bt k xc nhn no, v sau s gi phn hi ngc tr li cho pha client. Tp n bn pha client xc nhn phn hi t bn server gi v c cha thng tin mong mun hay khng.

b) HttpUnit

HttpUnit l mt th vin ngun m ca Java c dng tng tc vi cc server HTTP. Vi HttpUnit, chng trnh Java ca bn c th truy xut trc tip n server m khng cn thit phi s dng n trnh duyt.HttpUnit cung cp cc API phn tch HTML, nhn thng tin ca biu mu trang web, theo di cc siu lin kt, thit lp cookie v thc hin cc tc v khc c lin quan n trnh duyt web.Ngoi ra n cng gm c mt th vin thao tc trc tip n servlet, i khi khng cn thit phi khi ng web serverThng thng chng ta s dng kt hp HttpUnit v JUnit vit cc tt. JUnit nh ngha cc framework dng kim tra, v cc phng thc testXXX() ca bn s s dng cc hm API ca th vin HttpUnit truy cp v kim tra trang web

c) NUnit

NUnit l mt framework dnh cho vic testing unit trong tt c cc ngn ng .NET. Khi u n cng c bt u t JUnit, n l mt cng c h tr vic unit testing cho Microsoft.NET. N c vit hon ton bng C#

DEMO

CM N THY V CC BN THEO DI !!