-
Notifications
You must be signed in to change notification settings - Fork 0
JUnit 5: Creating a simple unit test using Gradle in Eclipse
-
Download and install Eclipse
-
Open Eclipse and go to File->New->Other
- In the new item window search for Gradle and select Gradle project
-
Give your project a name and click Finish
-
Delete all the text in the build.gradle file and add the following code below:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.1'
}
}
repositories {
mavenCentral()
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.junit.platform.gradle.plugin'
jar {
baseName = 'junit5-gradle-junit-demo'
version = '1.0.0-SNAPSHOT'
}
compileTestJava {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
dependencies {
testCompile("org.junit.jupiter:junit-jupiter-api:5.0.1")
testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.1")
}
- Right click on the src/test/ folder in the project and select New->JUnit Test Case (You may have to go to Other and search for JUnit Test Case in the New Item window if it doesn't show up)
- Select New JUnit Jupiter test and change the Source Folder to the /src/test/java folder. Fill in the Package (you can leave this blank and it will use the default package which isn't recommended) and Name fields. Make sure the class name has Test in it so that it's picked up by JUnit.
Now you should have a class with some code that looks something like this:
package codes.kristina.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class BasicUnitTest {
@Test
void test() {
fail("Not yet implemented");
}
}
The import static org.junit.jupiter.api.Assertions.*; statement is used for processing assert conditions in tests.
The import org.junit.jupiter.api.Test; statement allows you to use the @Test annotation with is used to signal that a method is a test method.
The code below is a unit test that will always fail:
@Test
void test() {
fail("Not yet implemented");
}
To run this Unit test right click on the project folder and select Run As->JUnit test.
You should see a screen like this that shows the Unit test failed.
To to modify the unit test so that it will pass change the code from:
@Test
void test() {
fail("Not yet implemented");
}
to
@Test
void myFirstTest() {
assertEquals(4, 2 + 2);
}
Rerun the test. The assertEquals(4, 2 + 2);
code compares the results of 2 + 2 to 4 and if it's true the test will pass and if it's false the test will fail.
You can find a link to the finished code here.
Always Learning
- Home
- Websites
- Linux
- Java
- Gradle
- JUnit
- Database