開發程式最重要的事情就是測試我們的程式,Gradle支援JUnit和TestNG測試框架。我們開始學習如何自動化的測試程式。
(1)測試之道 sourceSets {
在gradle預設測試的目錄為src/test/java/<test_package>,如果你要修改測試的目錄可以參考下列範例
test {
java {
srcDir 'testSrc'
}
}}
- Junit
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.+'
}
$ gradle test
:compileJava
:processResources
:classes
:compileTestJava
:processTestResources
:testClasses
:test
BUILD SUCCESSFUL
- TestNG
testCompile 'org.testng:testng:6.5.1'
}
範例一 寫一個計算機,可以做四則運算(加、減、乘、除)並做測試
Gradle.build
apply plugin: 'java'
repositories{
flatDir{
dirs 'C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\lib'
}
mavenCentral()
}
dependencies {
compile group: 'org.springframework', name: 'servlet-api'
compile group: 'org.springframework', name: 'jsp-api'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
計算機的檔案: src/main/java/org/gradle/main/Calculator.java
實作計算機的基本操作。
package org.gradle.main;
public class Calculator {
public int sum(int a, int b){
return a+b;
}
public int minus(int a, int b){
return a-b ;
}
public int multiply(int a, int b){
return a*b ;
}
public int divide(int a, int b){
return a/b ;
}
}
測試計算機 :src/main/java/org/gradle/test/CalculatorTest.java
package org.gradle.test;
import org.gradle.main.Calculator;
import org.junit.Assert;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testSum(){
final Calculator calculator = new Calculator() ;
int sum = calculator.sum(1, 1) ;
int expectSum = 2 ;
Assert.assertEquals("1+1=",expectSum, sum);
}
@Test
public void testMinus(){
final Calculator calculator = new Calculator() ;
int sum = calculator.minus(1, 1) ;
int expectSum = 0 ;
Assert.assertEquals("1-1=",expectSum, sum);
}
@Test
public void testMultiply(){
final Calculator calculator = new Calculator() ;
int sum = calculator.multiply(5, 10) ;
int expectSum = 50 ;
Assert.assertEquals("5*10=",expectSum, sum);
}
@Test
public void testDivide(){
final Calculator calculator = new Calculator() ;
int sum = calculator.divide(10, 5) ;
int expectSum = 2 ;
Assert.assertEquals("10/5=",expectSum, sum);
}
}
執行指令 : $ > gradle test
留言
張貼留言