This section focuses on writing a Gradle (https://gradle.org/) build script that builds a single Gradle project referred to as Computation. The source code and tests for a Java application is available here: Computation.zip. It is your job to create/reorganize the folder called Computation, move sources and tests into that folder, and produce the Gradle build script build.gradle within this folder to automate the software build and testing process for this example project.
First, open a terminal, and ensure you have the newes version of Gradle (ver. 5.0+) installed with gradle --version
.
Follow the steps below and add the snippets listed here to build.gradle
, one after the other:
-
Create the following folder structure and a new build.gradle (empty) file within the Computation folder:
Computation ├── build.gradle └── src ├── main │ └── java │ ├── application │ │ └── CompApp.java │ ├── computation │ │ └── Computation.java │ └── view │ └── ComputationPage.java └── test └── java └── computation ├── AllTests.java ├── ComputationTestAddSubstract.java └── ComputationTestDivideMultiply.java
-
Add the
java
and theapplication
plugins to the build configuration script build.gradle.apply plugin: 'java' // This plugin has a predefined 'run' task that we can reuse to use Gradle to execute our application apply plugin: 'application'
-
Add JUnit libraries to the
dependencies
section.repositories { mavenCentral() } dependencies { testImplementation "junit:junit:4.12" }
-
Add and describe a new task
compile(type: JavaCompile)
to specify all source files (both application and test) and set the build/bin as destination dir to put all compiled class files in.task compile(type: JavaCompile) { classpath = sourceSets.main.compileClasspath classpath += sourceSets.test.runtimeClasspath sourceSets.test.java.outputDir = file('build/bin') sourceSets.main.java.outputDir = file('build/bin') }
NoteOne can specify source sets and their variables the following way: /* * specifying sourceSets is not necessary in this case, since * we are applying the default folder structure assumed by Gradle */ sourceSets { main { java { srcDir 'src/main/java' } } test { java { srcDir 'src/test/java'} } }
-
Specify the main class and run the application.
mainClassName='application.CompApp'
In the command line issue
gradle run
-
Describe the
jar
Gradle task (defined by thejava
plugin) to produce an executable jar file intodistributable/
.jar { destinationDir=file('distributable') manifest { // It is smart to reuse the name of the main class variable instead of hardcoding it attributes "Main-Class": "$mainClassName" } }
Note
|
The settings.gradle and its usage is to be shown later.
|