工作中遇到TestNG和JUnit 2種寫測試用例的插件,都有不同的使用方法
目前是在eclipse工具+Selenium
我們創(chuàng)建java project成功后,假設(shè)創(chuàng)建Sample project,包名package.com.test
Demo.java文件中,寫上
package com.test;
public class Sample {
public int abs(int n){
return (n>=0)?n:(-n);
}
public static void main(String[] args) throws Exception{
Sample s= new Sample();
s.abs(-5);
}
}
1. 使用TestNG
安裝插件,這個網(wǎng)上很多資料不說了
創(chuàng)建TestNG的class,然后在工程右鍵build path-->add extral jars,加入testng-xxx -jar包,文件放置的位置在eclipse安裝目錄下xxx/eclipse/plugins/org.testngxxx/lib/testng-jdkxxx.jar相關(guān)包
下面是NewTest.java文件的內(nèi)容
package com.testng.test;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import static org.junit.Assert.*;
import org.junit.*;
//引入要測試的類
import com.test.Sample;
public class NewTest {
private Sample sTest;
@Test
public void testAbs() {
assertEquals(sTest.abs(-5),5);
}
@Test
public void a(){
assertEquals(sTest.abs(0));
}
@BeforeTest
public void beforeTest() {
sTest =new Sample();
}
@AfterTest
public void afterTest() {
}
}
文件右鍵 run-->run as "TestNG Test"
可以看到運(yùn)行的結(jié)果了,多少成功,失敗
TestNG 執(zhí)行的順序是
setup()
testfunction()[testng在測試用例時,查看@Test annonation信息,所以加注釋很重要]
teardown()
用例執(zhí)行完,會有testcase失敗和成功的信息
這里我沒有用testng.xml,這是我下一步學(xué)習(xí)的知識
2. 使用JUnit
我們使用maven創(chuàng)建工程,可以打開指定工程pom.xml文件
看到這樣的信息
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
說明JUnit查看對應(yīng)的包已經(jīng)存在了,具體他們存放在xxx/repo/junit/junit version/各種jar或者文件
junit version有2個版本,一個4.7 一個3.8.1版本之間有個不同
主要是setup() teardown()在3.8.1上 在每個testcase之前都會調(diào)用setup()和teardown(),執(zhí)行次數(shù)和執(zhí)行testcase次數(shù)一致
主要是setup() teardown()在4.7上 在所有testcase之前都會調(diào)用setup()和teardown(),執(zhí)行次數(shù)各為一次
接著Sample project工程說,
右鍵左邊工程的sample-->new-->JUnit Testcase, 創(chuàng)建測試類,
點擊ok,創(chuàng)建成功了,然后在工程右鍵build path-->add extral jars,加入junit 4.7 jar包
打開com.junit.test類的TestAba.java文件
下面是怎么寫TestCase了
package com.junit.test;
import static org.junit.Assert.*;
import org.junit.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
//引入需要測試的類
import com.test.Sample;
public class TestAbs {
private Sample sTest;
@Before
public void setUp() throws Exception {
sTest = new Sample();
}
@After
public void tearDown() throws Exception {
}
@Test
public voidtest001() {
//fail("Not yet implemented");
assertEquals(sTest.abs(-5),5);
}
}
文件右鍵 run-->run as "JUnit Test"
可以看到運(yùn)行的結(jié)果了,多少成功,失敗
JUnit執(zhí)行的順序是
setUp()
testXXX() //junit只尋找test開始的字段來執(zhí)行
tearDown()