Bird
Raised Fist0
Selenium Javatesting~15 mins

Maven build lifecycle in Selenium Java - Build an Automation Script

Choose your learning style10 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

Practice

(1/5)
1. Which Maven build lifecycle phase is responsible for compiling the source code of a Java project?
easy
A. clean
B. test
C. package
D. compile

Solution

  1. Step 1: Understand Maven lifecycle phases

    Maven has phases like clean, compile, test, and package, each with a specific role.
  2. Step 2: Identify the phase for compiling source code

    The compile phase compiles the Java source code into bytecode.
  3. Final Answer:

    compile -> Option D
  4. Quick Check:

    Compile phase compiles code = compile [OK]
Hint: Compile phase always compiles source code [OK]
Common Mistakes:
  • Confusing 'test' phase with compiling code
  • Thinking 'package' compiles code
  • Assuming 'clean' compiles code
2. Which Maven command cleans the project by deleting the target directory?
easy
A. mvn clean
B. mvn compile
C. mvn package
D. mvn test

Solution

  1. Step 1: Recall Maven commands and their purposes

    mvn clean deletes the target directory, removing previous build files.
  2. Step 2: Match command to cleaning action

    Only mvn clean removes old build artifacts before a fresh build.
  3. Final Answer:

    mvn clean -> Option A
  4. Quick Check:

    Clean command deletes target folder = mvn clean [OK]
Hint: Clean command always removes old build files [OK]
Common Mistakes:
  • Using mvn package to clean project
  • Confusing mvn test with cleaning
  • Thinking mvn compile cleans files
3. What will happen if you run mvn test on a Maven project that has not been compiled yet?
medium
A. Tests will fail because code is not compiled
B. Maven will compile the code first, then run tests
C. Maven will skip compilation and run tests directly
D. Maven will only clean the project without running tests

Solution

  1. Step 1: Understand Maven lifecycle phase dependencies

    Running mvn test triggers all previous phases including compile automatically.
  2. Step 2: Predict behavior when code is not compiled

    Maven compiles code before running tests to ensure tests run on compiled classes.
  3. Final Answer:

    Maven will compile the code first, then run tests -> Option B
  4. Quick Check:

    Test phase runs compile first = compile then test [OK]
Hint: Test phase always runs compile first [OK]
Common Mistakes:
  • Assuming tests run without compiling
  • Thinking Maven skips compile phase
  • Confusing clean with test phase
4. You run mvn package but get an error saying tests failed. What is the best way to fix this without skipping tests?
medium
A. Run mvn package -DskipTests to skip tests
B. Run mvn compile only to compile code
C. Run mvn clean package to clean and rebuild
D. Delete the target folder manually and rerun mvn package

Solution

  1. Step 1: Understand the error cause

    Tests failed during package phase, so build stopped.
  2. Step 2: Choose a fix that cleans and rebuilds including tests

    Running mvn clean package removes old files and rebuilds fresh, running tests again.
  3. Final Answer:

    Run mvn clean package to clean and rebuild -> Option C
  4. Quick Check:

    Clean then package reruns tests = mvn clean package [OK]
Hint: Clean before package to fix test errors without skipping [OK]
Common Mistakes:
  • Skipping tests instead of fixing them
  • Only compiling without packaging
  • Manually deleting target folder is error-prone
5. You want to create a Maven build that cleans, compiles, runs tests, and packages your project in one command. Which command should you use?
hard
A. mvn clean package
B. mvn clean compile test package
C. mvn compile test package
D. mvn test package

Solution

  1. Step 1: Understand Maven lifecycle chaining

    Running a later phase runs all previous phases automatically.
  2. Step 2: Identify the shortest command that runs all phases

    mvn clean package runs clean, compile, test, and package in order.
  3. Final Answer:

    mvn clean package -> Option A
  4. Quick Check:

    Package phase runs all before it = mvn clean package [OK]
Hint: Run clean then package to do all steps in one [OK]
Common Mistakes:
  • Listing all phases explicitly is unnecessary
  • Skipping clean phase
  • Running test package without clean
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard