import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.*;
import java.util.stream.*;
public class GradleDependencySetupTest {
@Test
void testBuildGradleContainsJUnitDependency() throws IOException {
Path buildFile = Paths.get("build.gradle");
assertTrue(Files.exists(buildFile), "build.gradle file should exist");
try (Stream<String> lines = Files.lines(buildFile)) {
boolean containsJUnit = lines.anyMatch(line -> line.contains("testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3'"));
assertTrue(containsJUnit, "build.gradle must contain JUnit Jupiter dependency");
}
}
@Test
void testGradleTestTaskRunsSuccessfully() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder();
builder.command("gradle", "test");
builder.redirectErrorStream(true);
Process process = builder.start();
String output;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
output = reader.lines().collect(Collectors.joining("\n"));
}
int exitCode = process.waitFor();
assertEquals(0, exitCode, "Gradle test task should exit with code 0");
assertTrue(output.contains("BUILD SUCCESSFUL"), "Gradle build should be successful");
assertTrue(output.contains("Test run finished"), "Test run output should be present");
}
@Test
void testTestReportIsGenerated() {
Path reportDir = Paths.get("build", "reports", "tests", "test");
assertTrue(Files.exists(reportDir), "Test report directory should exist");
try (Stream<Path> files = Files.list(reportDir)) {
boolean hasHtmlReport = files.anyMatch(path -> path.toString().endsWith(".html"));
assertTrue(hasHtmlReport, "Test report HTML file should be present");
} catch (IOException e) {
fail("Failed to list test report directory");
}
}
}
This test class verifies the Gradle dependency setup for JUnit in three ways:
- testBuildGradleContainsJUnitDependency: Reads the
build.gradle file and checks if the JUnit Jupiter dependency line is present. This ensures the dependency is declared correctly. - testGradleTestTaskRunsSuccessfully: Runs the
gradle test command as a process, captures the output, and asserts the build is successful and tests run. This confirms Gradle can execute tests using the dependency. - testTestReportIsGenerated: Checks if the test report directory and HTML report file exist after running tests. This verifies that test results are generated and accessible.
Each test uses clear assertions with helpful messages. The code uses standard Java APIs and JUnit 5 assertions. This approach simulates a real-world verification of Gradle dependency setup and test execution.