Skip to content

Instantly share code, notes, and snippets.

@shankybnl
Last active July 3, 2017 08:59
Show Gist options
  • Save shankybnl/f358daf355fe2a1d4c308ed60f5cf8cf to your computer and use it in GitHub Desktop.
Save shankybnl/f358daf355fe2a1d4c308ed60f5cf8cf to your computer and use it in GitHub Desktop.
Java gradle project with Junit and JaCoCo example

Java gradle project with Junit and JaCoCo example

Pre-requisite: gradle and java is installed on your machine.

  1. Create a gradle project (using Eclipse IDE)

Image

  1. Inside the project you will see two folders main and test under src folder. Under main you write your development code and under test you write your unit (Junit) tests and integration tests.

  2. Add the below lines of code to your build.gradle file present in the root directory.

apply plugin: "jacoco" 
jacocoTestReport{
    reports {
            xml.enabled false
            csv.enabled false
            html.destination "${buildDir}/jacocoHtml"
    }
}

If Junit dependency is not present then add it:

dependencies {
     testCompile 'junit:junit:4.12'
}
  1. Create a Example.java class under main folder.
public class Example {
	
	 public long someRandomMethod(int a, int b) {
	    	
	    	if (a > 10 && b > 10){
	    		return a+b;
	    	}
	    	else{
	    		return a-b;
	    	}
	       
	    }
}
  1. To verify this method, we will be writing Junit test under test folder with name ExampleTest.java @Test annontation tells Junit that it is a test method to execute.
public class ExampleTest {

    @Test
	public void verifySomeRandomMethod() {
		Example junitTest = new Example();
		junitTest.someRandomMethod(10, 9);
	}
}
  1. Go to the root directory of your project. And execute the below command to execute Junit test.
gradle test
  1. Junit results report will be generated /JunitJacocoExample/build/reports/tests/test/classes/ExampleTest.html

  2. To generate code coverage report, execute the below command.

gradle jacocoTestReport
  1. Code coverage report will be generated /JunitJacocoExample/build/jacocoHtml/index.html

Code coverage at class level can be verified by navigating to Example.java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment