0
0
Selenium Javatesting~15 mins

Maven build lifecycle in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify Maven build lifecycle phases for a Selenium Java project
Preconditions (3)
Step 1: Open a terminal or command prompt
Step 2: Navigate to the root directory of the Selenium Java project
Step 3: Run the command 'mvn clean' to clean the project
Step 4: Verify that the target directory is deleted
Step 5: Run the command 'mvn compile' to compile the source code
Step 6: Verify that the compilation completes without errors
Step 7: Run the command 'mvn test' to execute the tests
Step 8: Verify that the Selenium tests run and pass successfully
Step 9: Run the command 'mvn package' to package the compiled code into a jar
Step 10: Verify that the jar file is created in the target directory
✅ Expected Result: Each Maven lifecycle phase runs successfully with expected outputs: clean removes target, compile compiles code, test runs Selenium tests passing, package creates jar file
Automation Requirements - Selenium with TestNG and Maven
Assertions Needed:
Verify target directory is deleted after 'mvn clean'
Verify compilation success after 'mvn compile'
Verify Selenium tests pass after 'mvn test'
Verify jar file exists after 'mvn package'
Best Practices:
Use ProcessBuilder to run Maven commands
Capture and log command output for debugging
Use assertions to verify expected outputs
Handle exceptions and timeouts gracefully
Automated Solution
Selenium Java
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MavenBuildLifecycleTest {

    private String runCommand(String command, String workingDir) throws Exception {
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(command.split(" "));
        builder.directory(new File(workingDir));
        Process process = builder.start();
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append(System.lineSeparator());
            }
        }
        int exitCode = process.waitFor();
        Assert.assertEquals(exitCode, 0, "Command failed: " + command);
        return output.toString();
    }

    @Test
    public void testMavenBuildLifecycle() throws Exception {
        String projectDir = System.getProperty("user.dir");
        Path targetDir = Paths.get(projectDir, "target");

        // 1. mvn clean
        runCommand("mvn clean", projectDir);
        Assert.assertFalse(Files.exists(targetDir), "Target directory should be deleted after clean");

        // 2. mvn compile
        String compileOutput = runCommand("mvn compile", projectDir);
        Assert.assertTrue(compileOutput.contains("BUILD SUCCESS"), "Compile phase should succeed");

        // 3. mvn test
        String testOutput = runCommand("mvn test", projectDir);
        Assert.assertTrue(testOutput.contains("BUILD SUCCESS"), "Tests should run and pass");
        Assert.assertTrue(testOutput.contains("Tests run:"), "Test results should be reported");

        // 4. mvn package
        String packageOutput = runCommand("mvn package", projectDir);
        Assert.assertTrue(packageOutput.contains("BUILD SUCCESS"), "Package phase should succeed");

        // Verify jar file exists
        File jarFile = targetDir.toFile().listFiles((dir, name) -> name.endsWith(".jar"))[0];
        Assert.assertNotNull(jarFile, "Jar file should be created in target directory");
        Assert.assertTrue(jarFile.exists(), "Jar file should exist");
    }
}

This test class automates the verification of Maven build lifecycle phases for a Selenium Java project.

The runCommand method runs Maven commands in the project directory and captures output. It asserts the command exits successfully.

The test method testMavenBuildLifecycle runs the lifecycle phases in order: clean, compile, test, and package. After each phase, it asserts expected results:

  • After clean, the target directory should be deleted.
  • After compile, the build output should contain "BUILD SUCCESS".
  • After test, tests should run and pass, verified by output containing "Tests run:" and "BUILD SUCCESS".
  • After package, a jar file should be created in the target directory.

This approach uses ProcessBuilder to run Maven commands, captures output for assertions, and uses TestNG assertions to validate each step. It is simple, clear, and follows best practices for external process execution and test verification.

Common Mistakes - 4 Pitfalls
Using Runtime.exec() without handling output streams
Hardcoding absolute paths for project directory
Not checking exit codes of Maven commands
Not verifying the existence of generated artifacts like jar files
Bonus Challenge

Now add data-driven testing to run the Maven lifecycle commands on three different Selenium Java projects located in different directories.

Show Hint