This is an automated email from the ASF dual-hosted git repository.

olamy pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-surefire.git


The following commit(s) were added to refs/heads/master by this push:
     new 9b5466464 Fix #1471: add runLastFailed to run only the tests that 
failed last time (#3595)
9b5466464 is described below

commit 9b54664640ff8f135b7dd2724fe27ba411191def
Author: Olivier Lamy <[email protected]>
AuthorDate: Sat Nov 14 18:47:27 2026 +1000

    Fix #1471: add runLastFailed to run only the tests that failed last time 
(#3595)
    
    * Fix #1471: add runLastFailed to run only the tests that failed last time
    
    With -Dsurefire.runLastFailed (or -Dfailsafe.runLastFailed) the plugin
    reads the XML reports of the previous run and only runs the tests that
    failed or had an error. Classes that never finished because the last run
    stopped early (fork crash, timeout, Maven killed) run again too, which
    also helps with #2258.
    
    If nothing failed, no tests run. If there are no reports yet, all tests
    run. The test parameter, includes and excludes still apply.
    
    A small hidden file next to the reports directory tells whether the last
    run finished.
    
    
    ---------
    
    Signed-off-by: Olivier Lamy <[email protected]>
---
 .../maven/plugin/failsafe/IntegrationTestMojo.java |  24 ++
 maven-surefire-common/pom.xml                      |  13 +
 .../plugin/surefire/AbstractSurefireMojo.java      | 147 ++++++++-
 .../surefire/lastfailed/LastFailedTests.java       | 103 ++++++
 .../lastfailed/LastFailedTestsResolver.java        | 306 ++++++++++++++++++
 .../surefire/lastfailed/RunInProgressMarker.java   |  95 ++++++
 .../AbstractSurefireMojoJava7PlusTest.java         |   5 +
 .../plugin/surefire/AbstractSurefireMojoTest.java  |  25 ++
 .../maven/plugin/surefire/MojoMocklessTest.java    |   5 +
 .../lastfailed/LastFailedTestsResolverTest.java    | 359 +++++++++++++++++++++
 .../lastfailed/RunInProgressMarkerTest.java        |  59 ++++
 .../apache/maven/plugin/surefire/SurefireMojo.java |  24 ++
 .../markdown/examples/rerun-failing-tests.md.vm    |   3 +
 .../site/markdown/examples/run-last-failed.md.vm   |  75 +++++
 maven-surefire-plugin/src/site/site.xml            |   1 +
 .../apache/maven/surefire/its/RunLastFailedIT.java | 160 +++++++++
 .../src/test/resources/run-last-failed/pom.xml     |  80 +++++
 .../src/test/java/lastfailed/ATest.java            |  26 ++
 .../src/test/java/lastfailed/BTest.java            |  44 +++
 .../src/test/java/lastfailed/CTest.java            |  40 +++
 .../src/test/java/lastfailed/DCrashTest.java       |  31 ++
 .../src/test/java/lastfailed/ETest.java            |  26 ++
 .../src/test/java/lastfailed/FooIT.java            |  33 ++
 23 files changed, 1681 insertions(+), 3 deletions(-)

diff --git 
a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java
 
b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java
index 66b085acc..6d146bf77 100644
--- 
a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java
+++ 
b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java
@@ -336,6 +336,21 @@ public class IntegrationTestMojo extends 
AbstractSurefireMojo {
     @Parameter(property = "failsafe.rerunFailingTestsCount", defaultValue = 
"0")
     private int rerunFailingTestsCount;
 
+    /**
+     * Runs only the tests that failed in the last run, e.g. {@code mvn verify 
-Dfailsafe.runLastFailed}.
+     * <br>
+     * It reads the XML reports of the last run, so don't run {@code clean} in 
between. It runs the tests that
+     * failed or had an error, and the test classes that didn't finish because 
the last run stopped early
+     * (fork crash, timeout, Maven killed). If nothing failed, no tests run. 
If there are no reports, all tests run.
+     * <br>
+     * Unlike {@code rerunFailingTestsCount}, which retries failing tests 
right away in the same run, this works
+     * across runs. The {@code test} parameter, includes and excludes still 
apply.
+     *
+     * @since 3.6.2
+     */
+    @Parameter(property = "failsafe.runLastFailed", defaultValue = "false")
+    private boolean runLastFailed;
+
     /**
      * (TestNG) List of &lt;suiteXmlFile&gt; elements specifying TestNG suite 
xml file locations.
      * The build fails if this is set.
@@ -595,6 +610,15 @@ protected int getRerunFailingTestsCount() {
         return rerunFailingTestsCount;
     }
 
+    @Override
+    protected boolean isRunLastFailed() {
+        return runLastFailed;
+    }
+
+    public void setRunLastFailed(boolean runLastFailed) {
+        this.runLastFailed = runLastFailed;
+    }
+
     @Override
     @SuppressWarnings("unchecked")
     protected void handleSummary(RunResult summary, Exception 
firstForkException)
diff --git a/maven-surefire-common/pom.xml b/maven-surefire-common/pom.xml
index a148c6274..e710003b4 100644
--- a/maven-surefire-common/pom.xml
+++ b/maven-surefire-common/pom.xml
@@ -52,6 +52,19 @@
       <artifactId>surefire-extensions-api</artifactId>
       <version>${project.version}</version>
     </dependency>
+    <dependency>
+      <!-- runLastFailed reads the XML reports of the last run -->
+      <groupId>org.apache.maven.surefire</groupId>
+      <artifactId>surefire-report-parser</artifactId>
+      <version>${project.version}</version>
+      <exclusions>
+        <!-- only needed by SurefireReportParser, which we don't use -->
+        <exclusion>
+          <groupId>org.codehaus.plexus</groupId>
+          <artifactId>plexus-utils</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
     <dependency>
       <groupId>org.apache.maven.surefire</groupId>
       <artifactId>surefire-booter</artifactId>
diff --git 
a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java
 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java
index 15d7e436d..12ff76bf4 100644
--- 
a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java
+++ 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java
@@ -75,6 +75,10 @@
 import 
org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter;
 import org.apache.maven.plugin.surefire.extensions.SurefireStatelessReporter;
 import 
org.apache.maven.plugin.surefire.extensions.SurefireStatelessTestsetInfoReporter;
+import 
org.apache.maven.plugin.surefire.extensions.junit5.JUnit5Xml30StatelessReporter;
+import org.apache.maven.plugin.surefire.lastfailed.LastFailedTests;
+import org.apache.maven.plugin.surefire.lastfailed.LastFailedTestsResolver;
+import org.apache.maven.plugin.surefire.lastfailed.RunInProgressMarker;
 import org.apache.maven.plugin.surefire.log.PluginConsoleLogger;
 import org.apache.maven.plugin.surefire.log.api.ConsoleLogger;
 import org.apache.maven.plugin.surefire.util.DependencyScanner;
@@ -988,6 +992,11 @@ public abstract class AbstractSurefireMojo extends 
AbstractMojo implements Suref
 
     protected abstract int getRerunFailingTestsCount();
 
+    /**
+     * @return {@code true} to run only what failed or didn't finish last time
+     */
+    protected abstract boolean isRunLastFailed();
+
     @Override
     public abstract List<String> getIncludes();
 
@@ -1049,6 +1058,12 @@ private String getDefaultExcludes() {
 
     private TestListResolver includedExcludedTests;
 
+    /**
+     * Tests picked by {@code runLastFailed}, written like the {@code test} 
parameter.
+     * Used instead of {@link #getTest()} when set.
+     */
+    private String lastFailedTests;
+
     private List<CommandLineOption> cli;
 
     @Override
@@ -1067,6 +1082,19 @@ public void execute() throws MojoExecutionException, 
MojoFailureException {
         try {
             if (verifyParameters() && !hasExecutedBefore()) {
                 DefaultScanResult scan = scanForTestClasses();
+                if (isRunLastFailed() && !scan.isEmpty()) {
+                    LastFailedTests lastFailed = resolveLastFailedTests(scan);
+                    if (lastFailed.getSelection() == 
LastFailedTests.Selection.NOTHING) {
+                        getConsoleLogger()
+                                .info("No failed or unfinished tests found in 
" + getReportsDirectory()
+                                        + ", nothing to run.");
+                        return;
+                    }
+                    if (lastFailed.getSelection() == 
LastFailedTests.Selection.SOME) {
+                        useLastFailedTests(lastFailed);
+                        scan = scanForTestClasses();
+                    }
+                }
                 if (scan.isEmpty()) {
                     switch (getEffectiveFailIfNoTests()) {
                         case COULD_NOT_RUN_DEFAULT_TESTS:
@@ -1099,6 +1127,103 @@ public void execute() throws MojoExecutionException, 
MojoFailureException {
         }
     }
 
+    /**
+     * Finds what failed or didn't finish in the last run.
+     */
+    private LastFailedTests resolveLastFailedTests(DefaultScanResult scan) 
throws MojoFailureException {
+        File reportsDirectory = getReportsDirectory();
+        if (hasForkPlaceholder(reportsDirectory)) {
+            getConsoleLogger()
+                    .warning("runLastFailed doesn't support a reportsDirectory 
with a fork or thread number ("
+                            + reportsDirectory + "), running all tests.");
+            return LastFailedTests.runAll();
+        }
+        if (isXmlReportDisabled()) {
+            getConsoleLogger()
+                    .warning("runLastFailed needs the XML reports, but they 
are disabled, running all tests.");
+            return LastFailedTests.runAll();
+        }
+
+        boolean phrasedClassNames = false;
+        boolean phrasedMethodNames = false;
+        if (statelessTestsetReporter instanceof JUnit5Xml30StatelessReporter) {
+            JUnit5Xml30StatelessReporter reporter = 
(JUnit5Xml30StatelessReporter) statelessTestsetReporter;
+            phrasedClassNames = reporter.getUsePhrasedTestCaseClassName();
+            phrasedMethodNames = reporter.getUsePhrasedTestCaseMethodName();
+        }
+
+        return new LastFailedTestsResolver(
+                        reportsDirectory,
+                        RunInProgressMarker.of(reportsDirectory),
+                        getReportNameSuffix(),
+                        phrasedClassNames,
+                        phrasedMethodNames,
+                        getConsoleLogger())
+                .resolve(scan.getClasses(), getSpecificTests());
+    }
+
+    /**
+     * Runs only the tests picked by {@code runLastFailed}.
+     */
+    private void useLastFailedTests(LastFailedTests lastFailed) {
+        List<String> parts = new ArrayList<>();
+        if (lastFailed.getFailedMethods() > 0) {
+            parts.add(lastFailed.getFailedMethods() + " failed test(s)");
+        }
+        if (lastFailed.getFailedClasses() > 0) {
+            parts.add(lastFailed.getFailedClasses() + " class(es) that failed 
outside a test");
+        }
+        if (lastFailed.getUnfinishedClasses() > 0) {
+            parts.add(lastFailed.getUnfinishedClasses() + " class(es) that 
didn't finish");
+        }
+        getConsoleLogger().info("Running only what went wrong last time: " + 
String.join(", ", parts) + ".");
+        getConsoleLogger().debug("runLastFailed tests: " + 
lastFailed.getTests());
+
+        lastFailedTests = lastFailed.getTests();
+        // drop the cached filters, they get rebuilt from lastFailedTests
+        specificTests = null;
+        includedExcludedTests = null;
+    }
+
+    private boolean isXmlReportDisabled() {
+        if (disableXmlReport != null) {
+            return disableXmlReport;
+        }
+        return statelessTestsetReporter != null && 
statelessTestsetReporter.isDisable();
+    }
+
+    private static boolean hasForkPlaceholder(File directory) {
+        return directory != null && 
directory.getPath().contains("${surefire.");
+    }
+
+    /**
+     * Writes a marker while tests run, so {@code runLastFailed} can later 
tell if this run finished.
+     * We write it on every run, not only with {@code runLastFailed}.
+     */
+    private RunInProgressMarker writeRunInProgressMarker(DefaultScanResult 
scanResult) {
+        File reportsDirectory = getReportsDirectory();
+        if (reportsDirectory == null || hasForkPlaceholder(reportsDirectory)) {
+            return null;
+        }
+        RunInProgressMarker marker = RunInProgressMarker.of(reportsDirectory);
+        try {
+            marker.write(scanResult.getClasses());
+        } catch (IOException e) {
+            getConsoleLogger().debug("Could not write " + marker.getFile() + 
": " + e.getMessage());
+        }
+        return marker;
+    }
+
+    private void deleteRunInProgressMarker(RunInProgressMarker marker) {
+        if (marker != null) {
+            try {
+                marker.delete();
+            } catch (IOException e) {
+                getConsoleLogger().debug("Could not delete " + 
marker.getFile() + ": " + e.getMessage());
+            }
+        }
+    }
+
     void setLogger(Logger logger) {
         this.logger = logger;
         this.consoleLogger = new PluginConsoleLogger(logger);
@@ -1253,6 +1378,7 @@ private void executeAfterPreconditionsChecked(@Nonnull 
DefaultScanResult scanRes
 
         RunResult current = noTestsRun();
 
+        RunInProgressMarker runInProgressMarker = 
writeRunInProgressMarker(scanResult);
         Exception firstForkException = null;
         for (ProviderInfo provider : providers) {
             try {
@@ -1268,6 +1394,11 @@ private void executeAfterPreconditionsChecked(@Nonnull 
DefaultScanResult scanRes
             current = failure(current, firstForkException);
         }
 
+        // keep the marker after a crash or timeout, so runLastFailed knows 
this run stopped early
+        if (firstForkException == null && !current.isTimeout()) {
+            deleteRunInProgressMarker(runInProgressMarker);
+        }
+
         handleSummary(current, firstForkException);
     }
 
@@ -1874,7 +2005,10 @@ private boolean requiresRunHistory() {
     }
 
     private PluginFailureReason getEffectiveFailIfNoTests() {
-        if (isSpecificTestSpecified()) {
+        if (lastFailedTests != null) {
+            // a test that failed last time may have been removed since, don't 
fail for that
+            return NONE;
+        } else if (isSpecificTestSpecified()) {
             return getFailIfNoSpecifiedTests() ? COULD_NOT_RUN_SPECIFIED_TESTS 
: NONE;
         } else {
             return getFailIfNoTests() ? COULD_NOT_RUN_DEFAULT_TESTS : NONE;
@@ -2232,7 +2366,14 @@ private StartupReportConfiguration 
getStartupReportConfiguration(
     }
 
     private boolean isSpecificTestSpecified() {
-        return isNotBlank(getTest());
+        return isNotBlank(getEffectiveTest());
+    }
+
+    /**
+     * @return the tests picked by {@code runLastFailed} if any, otherwise the 
{@code test} parameter
+     */
+    private String getEffectiveTest() {
+        return lastFailedTests != null ? lastFailedTests : getTest();
     }
 
     @Nonnull
@@ -2332,7 +2473,7 @@ private List<String> getIncludeList() throws 
MojoFailureException {
     private List<String> getIncludeList(boolean asScanList) throws 
MojoFailureException {
         final List<String> includes = new ArrayList<>();
         if (isSpecificTestSpecified()) {
-            addAll(includes, split(getTest(), ","));
+            addAll(includes, split(getEffectiveTest(), ","));
         } else {
             if (asScanList) {
                 if (getIncludes() != null) {
diff --git 
a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTests.java
 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTests.java
new file mode 100644
index 000000000..4a28e0575
--- /dev/null
+++ 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTests.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugin.surefire.lastfailed;
+
+/**
+ * What {@code runLastFailed} should run.
+ */
+public final class LastFailedTests {
+    /**
+     * The possible outcomes.
+     */
+    public enum Selection {
+        /** We don't know what failed (e.g. no reports yet), run the usual 
tests. */
+        RUN_ALL,
+        /** Everything passed last time, nothing to run. */
+        NOTHING,
+        /** Run only the tests in {@link #getTests()}. */
+        SOME
+    }
+
+    private static final LastFailedTests RUN_ALL = new 
LastFailedTests(Selection.RUN_ALL, null, 0, 0, 0);
+
+    private static final LastFailedTests NOTHING = new 
LastFailedTests(Selection.NOTHING, null, 0, 0, 0);
+
+    private final Selection selection;
+
+    private final String tests;
+
+    private final int failedMethods;
+
+    private final int failedClasses;
+
+    private final int unfinishedClasses;
+
+    private LastFailedTests(
+            Selection selection, String tests, int failedMethods, int 
failedClasses, int unfinishedClasses) {
+        this.selection = selection;
+        this.tests = tests;
+        this.failedMethods = failedMethods;
+        this.failedClasses = failedClasses;
+        this.unfinishedClasses = unfinishedClasses;
+    }
+
+    public static LastFailedTests runAll() {
+        return RUN_ALL;
+    }
+
+    static LastFailedTests nothing() {
+        return NOTHING;
+    }
+
+    static LastFailedTests some(String tests, int failedMethods, int 
failedClasses, int unfinishedClasses) {
+        return new LastFailedTests(Selection.SOME, tests, failedMethods, 
failedClasses, unfinishedClasses);
+    }
+
+    public Selection getSelection() {
+        return selection;
+    }
+
+    /**
+     * @return the tests to run, written like the {@code test} parameter, only 
set for {@link Selection#SOME}
+     */
+    public String getTests() {
+        return tests;
+    }
+
+    /**
+     * @return the number of failed test methods to run
+     */
+    public int getFailedMethods() {
+        return failedMethods;
+    }
+
+    /**
+     * @return the number of classes that failed outside a test, e.g. in 
{@code @BeforeAll}
+     */
+    public int getFailedClasses() {
+        return failedClasses;
+    }
+
+    /**
+     * @return the number of classes that didn't finish because the last run 
stopped early
+     */
+    public int getUnfinishedClasses() {
+        return unfinishedClasses;
+    }
+}
diff --git 
a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTestsResolver.java
 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTestsResolver.java
new file mode 100644
index 000000000..4b39cdc89
--- /dev/null
+++ 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTestsResolver.java
@@ -0,0 +1,306 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugin.surefire.lastfailed;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.apache.maven.plugin.surefire.log.api.ConsoleLogger;
+import org.apache.maven.plugins.surefire.report.ReportTestCase;
+import org.apache.maven.plugins.surefire.report.ReportTestSuite;
+import org.apache.maven.plugins.surefire.report.TestSuiteXmlParser;
+import org.apache.maven.surefire.api.testset.ResolvedTest;
+import org.apache.maven.surefire.api.testset.TestListResolver;
+
+import static java.util.Collections.singletonList;
+import static 
org.apache.maven.surefire.api.testset.TestListResolver.toClassFileName;
+import static org.apache.maven.surefire.shared.lang3.StringUtils.isBlank;
+
+/**
+ * Finds the tests to run again for {@code runLastFailed}, by reading the XML 
reports of the last run.
+ * <br>
+ * It picks the test methods that failed, and the classes that didn't finish 
because the last run stopped
+ * early. The result uses the {@code -Dtest} syntax and never goes beyond what 
the user asked for.
+ */
+public final class LastFailedTestsResolver {
+    private static final String REPORT_PREFIX = "TEST-";
+
+    private static final String REPORT_EXTENSION = ".xml";
+
+    private final File reportsDirectory;
+
+    private final RunInProgressMarker marker;
+
+    private final String reportNameSuffix;
+
+    private final boolean phrasedClassNames;
+
+    private final boolean phrasedMethodNames;
+
+    private final ConsoleLogger logger;
+
+    /**
+     * @param reportsDirectory where the last run wrote its {@code TEST-*.xml} 
files
+     * @param marker tells us if the last run finished
+     * @param reportNameSuffix the {@code reportNameSuffix} parameter, added 
to class names in the reports
+     * @param phrasedClassNames the reports show display names instead of 
class names
+     * @param phrasedMethodNames the reports show display names instead of 
method names
+     * @param logger where to log
+     */
+    public LastFailedTestsResolver(
+            File reportsDirectory,
+            RunInProgressMarker marker,
+            String reportNameSuffix,
+            boolean phrasedClassNames,
+            boolean phrasedMethodNames,
+            ConsoleLogger logger) {
+        this.reportsDirectory = reportsDirectory;
+        this.marker = marker;
+        this.reportNameSuffix = reportNameSuffix;
+        this.phrasedClassNames = phrasedClassNames;
+        this.phrasedMethodNames = phrasedMethodNames;
+        this.logger = logger;
+    }
+
+    /**
+     * @param scannedClasses the test classes this run would normally run
+     * @param userFilter what the user asked for: {@code -Dtest}, includes and 
excludes
+     * @return the tests to run
+     */
+    public LastFailedTests resolve(Collection<String> scannedClasses, 
TestListResolver userFilter) {
+        if (phrasedClassNames) {
+            logger.warning("runLastFailed can't map display names in the XML 
reports back to test classes"
+                    + " (usePhrasedTestCaseClassName is on), running all 
tests.");
+            return LastFailedTests.runAll();
+        }
+
+        List<ReportTestSuite> suites = readReports();
+        Set<String> unfinishedRunClasses = null;
+        long unfinishedRunStart = 0;
+        if (marker.exists()) {
+            try {
+                unfinishedRunStart = marker.getStartTime();
+                unfinishedRunClasses = marker.readTestClasses();
+            } catch (IOException e) {
+                logger.warning("Could not read " + marker.getFile() + ": " + 
e.getMessage());
+            }
+        }
+
+        if (suites.isEmpty() && unfinishedRunClasses == null) {
+            logger.info("No reports from a previous run in " + 
reportsDirectory + ", running all tests.");
+            return LastFailedTests.runAll();
+        }
+
+        Set<String> scannedTopLevelClasses = new HashSet<>();
+        for (String scannedClass : scannedClasses) {
+            scannedTopLevelClasses.add(topLevelClass(scannedClass));
+        }
+
+        // sorted, so the result is always the same
+        Map<String, Set<String>> failedMethods = new TreeMap<>();
+        Set<String> failedClasses = new TreeSet<>();
+        for (ReportTestSuite suite : suites) {
+            for (ReportTestCase testCase : suite.getTestCases()) {
+                if (!testCase.hasFailure() && !testCase.hasError()) {
+                    continue;
+                }
+                String className = toClassName(testCase.getFullClassName());
+                if (className == null || 
!scannedTopLevelClasses.contains(topLevelClass(className))) {
+                    // the class is gone, or this run doesn't include it
+                    logger.debug("runLastFailed ignores " + 
testCase.getFullName() + ", not a test class of this run");
+                    continue;
+                }
+                String classFile = toClassFileName(className);
+                String methodName = phrasedMethodNames ? null : 
toMethodName(testCase.getName(), className);
+                if (methodName == null) {
+                    if (userFilter.shouldRun(classFile, null)) {
+                        failedClasses.add(className);
+                    }
+                } else if (userFilter.shouldRun(classFile, methodName)) {
+                    failedMethods
+                            .computeIfAbsent(className, c -> new TreeSet<>())
+                            .add(methodName);
+                }
+            }
+        }
+
+        Set<String> unfinishedClasses = new TreeSet<>();
+        if (unfinishedRunClasses != null) {
+            Set<String> finishedTopLevelClasses = new HashSet<>();
+            for (ReportTestSuite suite : suites) {
+                String className = toClassName(suite.getFullClassName());
+                if (className != null && suite.getLastModified() >= 
unfinishedRunStart) {
+                    finishedTopLevelClasses.add(topLevelClass(className));
+                }
+            }
+            for (String className : unfinishedRunClasses) {
+                String topLevelClass = topLevelClass(className);
+                if (scannedTopLevelClasses.contains(topLevelClass)
+                        && !finishedTopLevelClasses.contains(topLevelClass)
+                        && userFilter.shouldRun(toClassFileName(className), 
null)) {
+                    unfinishedClasses.add(className);
+                }
+            }
+            unfinishedClasses.removeAll(failedClasses);
+        }
+
+        Set<String> wholeClasses = new TreeSet<>(failedClasses);
+        wholeClasses.addAll(unfinishedClasses);
+
+        List<String> tests = new ArrayList<>();
+        for (String className : wholeClasses) {
+            tests.addAll(wholeClassPatterns(className, userFilter));
+        }
+        int failedMethodCount = 0;
+        for (Map.Entry<String, Set<String>> entry : failedMethods.entrySet()) {
+            // no need to list the failed methods of a class we run whole
+            if (!wholeClasses.contains(entry.getKey())) {
+                tests.add(entry.getKey() + "#" + String.join("+", 
entry.getValue()));
+                failedMethodCount += entry.getValue().size();
+            }
+        }
+
+        if (tests.isEmpty()) {
+            return LastFailedTests.nothing();
+        }
+
+        // keep the user's excludes
+        for (ResolvedTest excluded : userFilter.getExcludedPatterns()) {
+            String pattern = excluded.toString();
+            if (!pattern.isEmpty()) {
+                tests.add("!" + pattern);
+            }
+        }
+
+        return LastFailedTests.some(
+                String.join(",", tests), failedMethodCount, 
failedClasses.size(), unfinishedClasses.size());
+    }
+
+    /**
+     * Stays inside the user's filter: with {@code -Dtest=FooTest#a} we run 
{@code FooTest#a},
+     * not the whole {@code FooTest}.
+     */
+    private static List<String> wholeClassPatterns(String className, 
TestListResolver userFilter) {
+        String classFile = toClassFileName(className);
+        List<String> patterns = new ArrayList<>();
+        for (ResolvedTest included : userFilter.getIncludedPatterns()) {
+            if (included.matchAsInclusive(classFile, null)) {
+                if (!included.hasTestMethodPattern() || 
included.isRegexTestMethodPattern()) {
+                    // we can't mix a regex with our class name, so run the 
whole class
+                    return singletonList(className);
+                }
+                patterns.add(className + "#" + 
included.getTestMethodPattern());
+            }
+        }
+        return patterns.isEmpty() ? singletonList(className) : patterns;
+    }
+
+    private List<ReportTestSuite> readReports() {
+        File[] reports = reportsDirectory.listFiles(
+                (dir, name) -> name.startsWith(REPORT_PREFIX) && 
name.endsWith(REPORT_EXTENSION));
+        if (reports == null) {
+            return Collections.emptyList();
+        }
+        List<ReportTestSuite> suites = new ArrayList<>();
+        for (File report : reports) {
+            try {
+                suites.addAll(new 
TestSuiteXmlParser(logger).parse(report.getAbsolutePath()));
+            } catch (Exception e) {
+                // e.g. a report cut short when the run was killed
+                logger.warning("runLastFailed skips the report " + report + ", 
it can't be read: " + e.getMessage());
+            }
+        }
+        return suites;
+    }
+
+    /**
+     * Removes the {@code (reportNameSuffix)} we add to class names in the 
reports.
+     */
+    private String toClassName(String reportClassName) {
+        if (isBlank(reportClassName)) {
+            return null;
+        }
+        String className = reportClassName.trim();
+        if (!isBlank(reportNameSuffix)) {
+            String suffix = "(" + reportNameSuffix + ")";
+            if (className.endsWith(suffix)) {
+                className = className.substring(0, className.length() - 
suffix.length());
+            }
+        }
+        return className.isEmpty() ? null : className;
+    }
+
+    /**
+     * Gets the Java method name from a test name in the report, e.g. {@code 
square} from
+     * {@code square(int, int)[1]}.
+     *
+     * @return the method name, or {@code null} when we should run the whole 
class instead
+     */
+    static String toMethodName(String testName, String className) {
+        if (isBlank(testName)) {
+            return null;
+        }
+        String name = testName.trim();
+        for (int i = 0; i < name.length(); i++) {
+            char c = name.charAt(i);
+            if (c == '(' || c == '[') {
+                name = name.substring(0, i).trim();
+                break;
+            }
+        }
+        if (name.isEmpty()
+                || name.equals("initializationError")
+                || name.equals("executionError")
+                || name.equals(className)
+                || name.equals(simpleClassName(className))
+                || !Character.isJavaIdentifierStart(name.charAt(0))) {
+            return null;
+        }
+        for (int i = 1; i < name.length(); i++) {
+            if (!Character.isJavaIdentifierPart(name.charAt(i))) {
+                return null;
+            }
+        }
+        return name;
+    }
+
+    private static String simpleClassName(String className) {
+        int dot = className.lastIndexOf('.');
+        String simpleName = dot == -1 ? className : className.substring(dot + 
1);
+        int dollar = simpleName.lastIndexOf('$');
+        return dollar == -1 ? simpleName : simpleName.substring(dollar + 1);
+    }
+
+    /**
+     * Returns {@code a.b.Outer} for {@code a.b.Outer$Inner}. The scanner only 
lists outer classes.
+     */
+    static String topLevelClass(String className) {
+        int dollar = className.indexOf('$');
+        return dollar == -1 ? className : className.substring(0, dollar);
+    }
+}
diff --git 
a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/RunInProgressMarker.java
 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/RunInProgressMarker.java
new file mode 100644
index 000000000..4c1165bc8
--- /dev/null
+++ 
b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/lastfailed/RunInProgressMarker.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugin.surefire.lastfailed;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * A small file that exists while tests run, and is deleted when the run ends.
+ * If it is still there next time, the last run didn't finish: a fork crashed, 
timed out, or Maven was killed.
+ * <br>
+ * It lists the test classes of that run, and its date is when the run started.
+ * It sits next to the reports directory, e.g. {@code 
target/.surefire-reports-run-in-progress},
+ * so we never create or change the reports directory itself.
+ */
+public final class RunInProgressMarker {
+    private final File file;
+
+    private RunInProgressMarker(File file) {
+        this.file = file;
+    }
+
+    /**
+     * @param reportsDirectory where the XML reports are written
+     * @return the marker for this reports directory
+     */
+    public static RunInProgressMarker of(File reportsDirectory) {
+        File directory = reportsDirectory.getAbsoluteFile();
+        return new RunInProgressMarker(
+                new File(directory.getParentFile(), "." + directory.getName() 
+ "-run-in-progress"));
+    }
+
+    public File getFile() {
+        return file;
+    }
+
+    public boolean exists() {
+        return file.isFile();
+    }
+
+    /**
+     * Writes the test classes about to run, replacing any old marker.
+     */
+    public void write(Collection<String> testClasses) throws IOException {
+        Files.createDirectories(file.toPath().getParent());
+        Files.write(file.toPath(), testClasses, UTF_8);
+    }
+
+    public void delete() throws IOException {
+        Files.deleteIfExists(file.toPath());
+    }
+
+    /**
+     * @return when the run started
+     */
+    long getStartTime() {
+        return file.lastModified();
+    }
+
+    /**
+     * @return the test classes of the run
+     */
+    Set<String> readTestClasses() throws IOException {
+        Set<String> classes = new LinkedHashSet<>();
+        for (String line : Files.readAllLines(file.toPath(), UTF_8)) {
+            String className = line.trim();
+            if (!className.isEmpty()) {
+                classes.add(className);
+            }
+        }
+        return classes;
+    }
+}
diff --git 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java
 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java
index db14fce08..ad5b5448a 100644
--- 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java
+++ 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java
@@ -581,6 +581,11 @@ protected int getRerunFailingTestsCount() {
             return 0;
         }
 
+        @Override
+        protected boolean isRunLastFailed() {
+            return false;
+        }
+
         @Override
         public boolean isSkipTests() {
             return false;
diff --git 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java
 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java
index 2366ff04a..b12553b8a 100644
--- 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java
+++ 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java
@@ -2157,6 +2157,11 @@ protected int getRerunFailingTestsCount() {
             return 0;
         }
 
+        @Override
+        protected boolean isRunLastFailed() {
+            return false;
+        }
+
         @Override
         public boolean isSkipTests() {
             return false;
@@ -2652,6 +2657,26 @@ public void shouldIgnoreMethodExcludesWhenTestIsSet() 
throws Exception {
         assertThat(specificTests.shouldRun("AnotherTest.class", 
"method")).isTrue();
     }
 
+    @Test
+    public void shouldUseLastFailedTestsInsteadOfTheTestParameter() throws 
Exception {
+        Mojo plugin = new Mojo();
+
+        plugin.setExcludes(singletonList("**/SlowTest.java"));
+        plugin.setTest("FooTest");
+
+        setInternalState(plugin, "lastFailedTests", 
"pkg.FooTest#b,!pkg.FooTest#c");
+
+        TestListResolver specificTests = plugin.getSpecificTests();
+        assertThat(specificTests.shouldRun("pkg/FooTest.class", "b")).isTrue();
+        assertThat(specificTests.shouldRun("pkg/FooTest.class", 
"a")).isFalse();
+        assertThat(specificTests.shouldRun("pkg/FooTest.class", 
"c")).isFalse();
+        assertThat(specificTests.shouldRun("pkg/OtherTest.class", 
null)).isFalse();
+        // a failed test may have been removed since, that's not a failure
+        assertThat(invokeMethod(plugin, 
"getEffectiveFailIfNoTests").toString()).isEqualTo("NONE");
+        // the test parameter doesn't change, so neither does the config 
checksum
+        assertThat(plugin.getTest()).isEqualTo("FooTest");
+    }
+
     @Test
     public void shouldUseOnlySpecificTests() throws Exception {
         Mojo plugin = new Mojo();
diff --git 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java
 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java
index 7acf75bd1..c330f6521 100644
--- 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java
+++ 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java
@@ -369,6 +369,11 @@ protected int getRerunFailingTestsCount() {
             return 0;
         }
 
+        @Override
+        protected boolean isRunLastFailed() {
+            return false;
+        }
+
         @Override
         public boolean isSkipTests() {
             return false;
diff --git 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTestsResolverTest.java
 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTestsResolverTest.java
new file mode 100644
index 000000000..47bd2b92b
--- /dev/null
+++ 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/lastfailed/LastFailedTestsResolverTest.java
@@ -0,0 +1,359 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugin.surefire.lastfailed;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.maven.plugin.surefire.lastfailed.LastFailedTests.Selection;
+import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger;
+import org.apache.maven.surefire.api.testset.TestListResolver;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class LastFailedTestsResolverTest {
+    private static final TestListResolver NO_FILTER = 
TestListResolver.getEmptyTestListResolver();
+
+    @TempDir
+    Path tempDir;
+
+    private File reportsDirectory;
+
+    private RunInProgressMarker marker;
+
+    @BeforeEach
+    void setUp() {
+        reportsDirectory = tempDir.resolve("surefire-reports").toFile();
+        assertThat(reportsDirectory.mkdirs()).isTrue();
+        marker = RunInProgressMarker.of(reportsDirectory);
+    }
+
+    @Test
+    void runsAllWithoutPreviousReports() {
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), 
NO_FILTER);
+
+        assertThat(result.getSelection()).isEqualTo(Selection.RUN_ALL);
+    }
+
+    @Test
+    void runsAllWhenTheReportsDirectoryIsMissing() {
+        File missing = new File(reportsDirectory, "missing");
+        LastFailedTests result = new LastFailedTestsResolver(
+                        missing, RunInProgressMarker.of(missing), null, false, 
false, new NullConsoleLogger())
+                .resolve(singletonList("pkg.FooTest"), NO_FILTER);
+
+        assertThat(result.getSelection()).isEqualTo(Selection.RUN_ALL);
+    }
+
+    @Test
+    void picksFailuresAndErrors() throws IOException {
+        report("pkg.FooTest", passed("pkg.FooTest", "a"), 
failed("pkg.FooTest", "b"), error("pkg.FooTest", "c"));
+        report("pkg.BarTest", passed("pkg.BarTest", "a"));
+
+        LastFailedTests result = resolve(asList("pkg.FooTest", "pkg.BarTest"), 
NO_FILTER);
+
+        assertThat(result.getSelection()).isEqualTo(Selection.SOME);
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest#b+c");
+        assertThat(result.getFailedMethods()).isEqualTo(2);
+        assertThat(result.getFailedClasses()).isZero();
+        assertThat(result.getUnfinishedClasses()).isZero();
+
+        TestListResolver filter = new TestListResolver(result.getTests());
+        assertThat(filter.shouldRun("pkg/FooTest.class", "b")).isTrue();
+        assertThat(filter.shouldRun("pkg/FooTest.class", "c")).isTrue();
+        assertThat(filter.shouldRun("pkg/FooTest.class", "a")).isFalse();
+        assertThat(filter.shouldRun("pkg/BarTest.class", null)).isFalse();
+    }
+
+    @Test
+    void leavesOutFlakyAndSkippedTests() throws IOException {
+        report("pkg.FooTest", flaky("pkg.FooTest", "a"), 
skipped("pkg.FooTest", "b"), passed("pkg.FooTest", "c"));
+
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), 
NO_FILTER);
+
+        assertThat(result.getSelection()).isEqualTo(Selection.NOTHING);
+    }
+
+    @Test
+    void trimsParameterizedNames() throws IOException {
+        report(
+                "pkg.FooTest",
+                failed("pkg.FooTest", "square(int, int)[1]"),
+                failed("pkg.FooTest", "square(int, int)[2]"));
+        report("pkg.BarTest", failed("pkg.BarTest", "test[0]"));
+
+        LastFailedTests result = resolve(asList("pkg.FooTest", "pkg.BarTest"), 
NO_FILTER);
+
+        
assertThat(result.getTests()).isEqualTo("pkg.BarTest#test,pkg.FooTest#square");
+        assertThat(result.getFailedMethods()).isEqualTo(2);
+    }
+
+    @Test
+    void runsTheWholeClassWhenItFailedOutsideATest() throws IOException {
+        report("pkg.FooTest", failed("pkg.FooTest", "b"), error("pkg.FooTest", 
"initializationError"));
+        report("pkg.BarTest", error("pkg.BarTest", "executionError"));
+
+        LastFailedTests result = resolve(asList("pkg.FooTest", "pkg.BarTest"), 
NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.BarTest,pkg.FooTest");
+        assertThat(result.getFailedClasses()).isEqualTo(2);
+        assertThat(result.getFailedMethods()).isZero();
+    }
+
+    @Test
+    void runsTheWholeClassWhenTheNameIsNotAJavaMethod() throws IOException {
+        report("pkg.FooTest", failed("pkg.FooTest", "should add a, b and c"));
+
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), 
NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest");
+        assertThat(result.getFailedClasses()).isEqualTo(1);
+    }
+
+    @Test
+    void keepsTheBinaryNameOfNestedClasses() throws IOException {
+        report("pkg.FooTest", failed("pkg.FooTest$Inner", "m"));
+
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), 
NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest$Inner#m");
+        assertThat(new 
TestListResolver(result.getTests()).shouldRun("pkg/FooTest$Inner.class", "m"))
+                .isTrue();
+    }
+
+    @Test
+    void removesTheReportNameSuffix() throws IOException {
+        report("pkg.FooTest-jdk17", failed("pkg.FooTest(jdk17)", "b"));
+
+        LastFailedTests result = new LastFailedTestsResolver(
+                        reportsDirectory, marker, "jdk17", false, false, new 
NullConsoleLogger())
+                .resolve(singletonList("pkg.FooTest"), NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest#b");
+    }
+
+    @Test
+    void ignoresClassesThatAreNotPartOfThisRun() throws IOException {
+        report("pkg.GoneTest", failed("pkg.GoneTest", "a"));
+        report("pkg.FooTest", passed("pkg.FooTest", "a"));
+
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), 
NO_FILTER);
+
+        assertThat(result.getSelection()).isEqualTo(Selection.NOTHING);
+    }
+
+    @Test
+    void staysInsideTheMethodsOfTheTestParameter() throws IOException {
+        report("pkg.FooTest", failed("pkg.FooTest", "a"), 
failed("pkg.FooTest", "b"));
+
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), new 
TestListResolver("FooTest#a"));
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest#a");
+    }
+
+    @Test
+    void keepsTheExcludesOfTheTestParameter() throws IOException {
+        report("pkg.FooTest", failed("pkg.FooTest", "a"), 
failed("pkg.FooTest", "slow"));
+
+        LastFailedTests result =
+                resolve(singletonList("pkg.FooTest"), new 
TestListResolver("Foo*, !FooTest#slow, !FooSlowTest"));
+
+        
assertThat(result.getTests()).isEqualTo("pkg.FooTest#a,!FooTest#slow,!FooSlowTest");
+        TestListResolver filter = new TestListResolver(result.getTests());
+        assertThat(filter.shouldRun("pkg/FooTest.class", "a")).isTrue();
+        assertThat(filter.shouldRun("pkg/FooSlowTest.class", null)).isFalse();
+    }
+
+    @Test
+    void runsClassesThatDidNotFinishWhenThePreviousRunStoppedEarly() throws 
IOException {
+        marker.write(asList("pkg.ATest", "pkg.BTest", "pkg.CTest"));
+        long runStart = System.currentTimeMillis() - 60_000;
+        assertThat(marker.getFile().setLastModified(runStart)).isTrue();
+        // ATest finished before the run stopped
+        setLastModified(report("pkg.ATest", passed("pkg.ATest", "a")), 
runStart + 10_000);
+        // BTest only has an older report, from an earlier run
+        setLastModified(report("pkg.BTest", failed("pkg.BTest", "b")), 
runStart - 10_000);
+        // CTest has no report at all
+
+        LastFailedTests result = resolve(asList("pkg.ATest", "pkg.BTest", 
"pkg.CTest"), NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.BTest,pkg.CTest");
+        assertThat(result.getUnfinishedClasses()).isEqualTo(2);
+        assertThat(result.getFailedMethods()).isZero();
+    }
+
+    @Test
+    void ignoresClassesWithoutReportsWhenThePreviousRunFinished() throws 
IOException {
+        // e.g. an abstract base class named *Test never gets a report
+        report("pkg.ATest", passed("pkg.ATest", "a"));
+
+        LastFailedTests result = resolve(asList("pkg.ATest", 
"pkg.AbstractBaseTest"), NO_FILTER);
+
+        assertThat(result.getSelection()).isEqualTo(Selection.NOTHING);
+    }
+
+    @Test
+    void runsEverythingTheStoppedRunWantedWhenNoReportWasWritten() throws 
IOException {
+        marker.write(asList("pkg.ATest", "pkg.BTest"));
+
+        LastFailedTests result = resolve(asList("pkg.ATest", "pkg.BTest", 
"pkg.NewTest"), NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.ATest,pkg.BTest");
+    }
+
+    @Test
+    void narrowsUnfinishedClassesToTheMethodsOfTheTestParameter() throws 
IOException {
+        marker.write(singletonList("pkg.FooTest"));
+
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), new 
TestListResolver("FooTest#a+b"));
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest#a,pkg.FooTest#b");
+        TestListResolver filter = new TestListResolver(result.getTests());
+        assertThat(filter.shouldRun("pkg/FooTest.class", "a")).isTrue();
+        assertThat(filter.shouldRun("pkg/FooTest.class", "c")).isFalse();
+    }
+
+    @Test
+    void runsTheWholeUnfinishedClassWhenTheTestParameterUsesARegex() throws 
IOException {
+        marker.write(singletonList("pkg.FooTest"));
+
+        LastFailedTests result = resolve(singletonList("pkg.FooTest"), new 
TestListResolver("%regex[.*FooTest.*#a.*]"));
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest");
+    }
+
+    @Test
+    void skipsReportsThatCantBeRead() throws IOException {
+        Files.write(new File(reportsDirectory, 
"TEST-pkg.BrokenTest.xml").toPath(), "<testsuite".getBytes(UTF_8));
+        report("pkg.FooTest", failed("pkg.FooTest", "b"));
+
+        LastFailedTests result = resolve(asList("pkg.FooTest", 
"pkg.BrokenTest"), NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest#b");
+    }
+
+    @Test
+    void runsAllWhenReportsUseDisplayNamesForClasses() throws IOException {
+        report("pkg.FooTest", failed("Foo display name", "b"));
+
+        LastFailedTests result = new LastFailedTestsResolver(
+                        reportsDirectory, marker, null, true, false, new 
NullConsoleLogger())
+                .resolve(singletonList("pkg.FooTest"), NO_FILTER);
+
+        assertThat(result.getSelection()).isEqualTo(Selection.RUN_ALL);
+    }
+
+    @Test
+    void runsWholeClassesWhenReportsUseDisplayNamesForMethods() throws 
IOException {
+        report("pkg.FooTest", failed("pkg.FooTest", "adds two numbers"));
+
+        LastFailedTests result = new LastFailedTestsResolver(
+                        reportsDirectory, marker, null, false, true, new 
NullConsoleLogger())
+                .resolve(singletonList("pkg.FooTest"), NO_FILTER);
+
+        assertThat(result.getTests()).isEqualTo("pkg.FooTest");
+    }
+
+    @Test
+    void readsTheMethodName() {
+        assertThat(LastFailedTestsResolver.toMethodName("test", 
"pkg.FooTest")).isEqualTo("test");
+        assertThat(LastFailedTestsResolver.toMethodName(" test(String)[1] ", 
"pkg.FooTest"))
+                .isEqualTo("test");
+        assertThat(LastFailedTestsResolver.toMethodName("test[0]", 
"pkg.FooTest"))
+                .isEqualTo("test");
+        assertThat(LastFailedTestsResolver.toMethodName("FooTest", 
"pkg.FooTest"))
+                .isNull();
+        assertThat(LastFailedTestsResolver.toMethodName("pkg.FooTest", 
"pkg.FooTest"))
+                .isNull();
+        assertThat(LastFailedTestsResolver.toMethodName("initializationError", 
"pkg.FooTest"))
+                .isNull();
+        assertThat(LastFailedTestsResolver.toMethodName("", 
"pkg.FooTest")).isNull();
+        assertThat(LastFailedTestsResolver.toMethodName("1test", 
"pkg.FooTest")).isNull();
+        assertThat(LastFailedTestsResolver.toMethodName("a+b", 
"pkg.FooTest")).isNull();
+    }
+
+    @Test
+    void readsTheTopLevelClass() {
+        
assertThat(LastFailedTestsResolver.topLevelClass("pkg.FooTest")).isEqualTo("pkg.FooTest");
+        
assertThat(LastFailedTestsResolver.topLevelClass("pkg.FooTest$A$B")).isEqualTo("pkg.FooTest");
+    }
+
+    private LastFailedTests resolve(List<String> scannedClasses, 
TestListResolver userFilter) {
+        return new LastFailedTestsResolver(reportsDirectory, marker, null, 
false, false, new NullConsoleLogger())
+                .resolve(scannedClasses, userFilter);
+    }
+
+    private File report(String fileName, String... testCases) throws 
IOException {
+        StringBuilder xml = new StringBuilder();
+        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
+                .append("<testsuite name=\"")
+                .append(fileName)
+                .append("\" time=\"0.1\" tests=\"")
+                .append(testCases.length)
+                .append("\">\n");
+        Arrays.stream(testCases).forEach(xml::append);
+        xml.append("</testsuite>\n");
+        File report = new File(reportsDirectory, "TEST-" + fileName + ".xml");
+        Files.write(report.toPath(), xml.toString().getBytes(UTF_8));
+        return report;
+    }
+
+    private static void setLastModified(File file, long time) {
+        assertThat(file.setLastModified(time)).isTrue();
+    }
+
+    private static String passed(String className, String name) {
+        return testCase(className, name, "");
+    }
+
+    private static String failed(String className, String name) {
+        return testCase(className, name, "<failure message=\"boom\" 
type=\"java.lang.AssertionError\">trace</failure>");
+    }
+
+    private static String error(String className, String name) {
+        return testCase(className, name, "<error message=\"boom\" 
type=\"java.lang.RuntimeException\">trace</error>");
+    }
+
+    private static String skipped(String className, String name) {
+        return testCase(className, name, "<skipped message=\"disabled\"/>");
+    }
+
+    private static String flaky(String className, String name) {
+        return testCase(
+                className,
+                name,
+                "<flakyFailure message=\"boom\" 
type=\"java.lang.AssertionError\">"
+                        + "<stackTrace>trace</stackTrace></flakyFailure>");
+    }
+
+    private static String testCase(String className, String name, String body) 
{
+        return "  <testcase name=\"" + name + "\" classname=\"" + className + 
"\" time=\"0.01\">" + body
+                + "</testcase>\n";
+    }
+}
diff --git 
a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/lastfailed/RunInProgressMarkerTest.java
 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/lastfailed/RunInProgressMarkerTest.java
new file mode 100644
index 000000000..1d3df0f60
--- /dev/null
+++ 
b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/lastfailed/RunInProgressMarkerTest.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugin.surefire.lastfailed;
+
+import java.io.IOException;
+import java.nio.file.Path;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class RunInProgressMarkerTest {
+    @TempDir
+    Path tempDir;
+
+    @Test
+    void sitsNextToTheReportsDirectory() {
+        Path reportsDirectory = tempDir.resolve("failsafe-reports");
+
+        assertThat(RunInProgressMarker.of(reportsDirectory.toFile()).getFile())
+                
.isEqualTo(tempDir.resolve(".failsafe-reports-run-in-progress").toFile());
+    }
+
+    @Test
+    void listsTheTestClassesOfTheRun() throws IOException {
+        Path reportsDirectory = tempDir.resolve("surefire-reports");
+        RunInProgressMarker marker = 
RunInProgressMarker.of(reportsDirectory.toFile());
+
+        marker.write(asList("pkg.ATest", "pkg.BTest"));
+
+        assertThat(marker.exists()).isTrue();
+        assertThat(marker.readTestClasses()).containsExactly("pkg.ATest", 
"pkg.BTest");
+        assertThat(marker.getStartTime()).isPositive();
+        // the reports directory is left alone
+        assertThat(reportsDirectory).doesNotExist();
+
+        marker.delete();
+
+        assertThat(marker.exists()).isFalse();
+    }
+}
diff --git 
a/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefireMojo.java
 
b/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefireMojo.java
index 84ea744e9..8b888f64b 100644
--- 
a/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefireMojo.java
+++ 
b/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefireMojo.java
@@ -290,6 +290,21 @@ public class SurefireMojo extends AbstractSurefireMojo 
implements SurefireReport
     @Parameter(property = "surefire.rerunFailingTestsCount", defaultValue = 
"0")
     private int rerunFailingTestsCount;
 
+    /**
+     * Runs only the tests that failed in the last run, e.g. {@code mvn test 
-Dsurefire.runLastFailed}.
+     * <br>
+     * It reads the XML reports of the last run, so don't run {@code clean} in 
between. It runs the tests that
+     * failed or had an error, and the test classes that didn't finish because 
the last run stopped early
+     * (fork crash, timeout, Maven killed). If nothing failed, no tests run. 
If there are no reports, all tests run.
+     * <br>
+     * Unlike {@code rerunFailingTestsCount}, which retries failing tests 
right away in the same run, this works
+     * across runs. The {@code test} parameter, includes and excludes still 
apply.
+     *
+     * @since 3.6.2
+     */
+    @Parameter(property = "surefire.runLastFailed", defaultValue = "false")
+    private boolean runLastFailed;
+
     /**
      * Set this to a value greater than 0 to fail the whole test set if the 
cumulative number of flakes reaches
      * this threshold. Set to 0 to allow an unlimited number of flakes.
@@ -557,6 +572,15 @@ protected int getRerunFailingTestsCount() {
         return rerunFailingTestsCount;
     }
 
+    @Override
+    protected boolean isRunLastFailed() {
+        return runLastFailed;
+    }
+
+    public void setRunLastFailed(boolean runLastFailed) {
+        this.runLastFailed = runLastFailed;
+    }
+
     @Override
     public int getFailOnFlakeCount() {
         return failOnFlakeCount;
diff --git 
a/maven-surefire-plugin/src/site/markdown/examples/rerun-failing-tests.md.vm 
b/maven-surefire-plugin/src/site/markdown/examples/rerun-failing-tests.md.vm
index a397e0b1f..db8ad84b7 100644
--- a/maven-surefire-plugin/src/site/markdown/examples/rerun-failing-tests.md.vm
+++ b/maven-surefire-plugin/src/site/markdown/examples/rerun-failing-tests.md.vm
@@ -36,6 +36,9 @@ mvn -D${thisPlugin.toLowerCase()}.rerunFailingTestsCount=2 
test
 
 If `rerunFailingTestsCount` is set to a value smaller than or equal to 0, then 
it will be ignored.
 
+The reruns happen straight away, within the same build. To run again, in a 
later build, only the tests that failed
+in the previous one, see [`runLastFailed`](./run-last-failed.html).
+
 Output flaky re-run information on the screen
 ---------------------------------------------
 
diff --git 
a/maven-surefire-plugin/src/site/markdown/examples/run-last-failed.md.vm 
b/maven-surefire-plugin/src/site/markdown/examples/run-last-failed.md.vm
new file mode 100644
index 000000000..75023e958
--- /dev/null
+++ b/maven-surefire-plugin/src/site/markdown/examples/run-last-failed.md.vm
@@ -0,0 +1,75 @@
+---
+title: Run only the tests that failed last time
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+#{if}(${project.artifactId}=="maven-surefire-plugin")
+#set($goal = "test")
+#{else}
+#set($goal = "verify")
+#{end}
+
+# Run Only the Tests That Failed Last Time
+
+Since 3.6.2, `runLastFailed` lets you run again only the tests that went wrong 
in the previous build.
+It helps with long test suites: a few tests failed, you fixed the code (or 
restarted that flaky external service),
+and you don't want to run everything again just to check them.
+
+```bash
+mvn ${goal}
+# a few tests fail, you fix them
+mvn -D${thisPlugin.toLowerCase()}.runLastFailed ${goal}
+```
+
+The previous build is read from the XML reports in `reportsDirectory`, so 
**don't run `clean` in between**.
+
+## What runs
+
+- Test methods that ended with a failure or an error. Tests that passed, were 
skipped or were flaky
+  (they failed but passed on a rerun) don't run again.
+- Whole test classes that didn't finish because the previous build stopped 
early: a crashed or killed forked JVM,
+  a `forkedProcessTimeoutInSeconds` timeout, or Maven itself being stopped. 
Tests that never had a chance to run
+  get their turn.
+
+If the previous build had no failures, no tests run and the plugin says so. If 
there are no reports yet,
+for instance right after `clean`, all tests run as usual.
+
+The `test` parameter, `includes` and `excludes` still apply. With 
`-Dtest=MyTest`, only the tests of `MyTest`
+that failed last time run.
+
+## Not the same as rerunFailingTestsCount
+
+[`rerunFailingTestsCount`](./rerun-failing-tests.html) retries a failing test 
straight away, within the same build,
+to deal with flaky tests. `runLastFailed` works across builds: it remembers 
what went wrong last time.
+You can use both together.
+
+## Good to know
+
+- After such a build, the report of each class that ran again only lists the 
tests that ran again.
+  The reports of the other classes are left untouched.
+- All the invocations of a parameterized test run again, not only the ones 
that failed.
+- A test class that failed outside a test method (e.g. in a `@BeforeAll` 
method) runs again in full.
+  So does a class whose failed test names can't be mapped back to a Java 
method, e.g. with
+  `usePhrasedTestCaseMethodName` in the `statelessTestsetReporter` 
configuration.
+- With `usePhrasedTestCaseClassName`, the reports don't hold the class names 
any more, so all tests run.
+- To know whether the previous build finished, the plugin keeps a small hidden 
file next to `reportsDirectory`
+  while the tests run, e.g. 
`target/.${thisPlugin.toLowerCase()}-reports-run-in-progress`.
+- A `reportsDirectory` containing `${esc.d}{surefire.forkNumber}` isn't 
supported, all tests run.
diff --git a/maven-surefire-plugin/src/site/site.xml 
b/maven-surefire-plugin/src/site/site.xml
index 4c44032a3..ceaae4744 100644
--- a/maven-surefire-plugin/src/site/site.xml
+++ b/maven-surefire-plugin/src/site/site.xml
@@ -54,6 +54,7 @@
       <item name="Inclusions and Exclusions of Tests" 
href="examples/inclusion-exclusion.html"/>
       <item name="Running a Single Test" href="examples/single-test.html"/>
       <item name="Re-run Failing Tests" 
href="examples/rerun-failing-tests.html"/>
+      <item name="Run Only Last Failed Tests" 
href="examples/run-last-failed.html"/>
       <item name="Class Loading and Forking" 
href="examples/class-loading.html"/>
       <item name="Debugging Tests" href="examples/debugging.html"/>
       <item name="Using System Properties" 
href="examples/system-properties.html"/>
diff --git 
a/surefire-its/src/test/java/org/apache/maven/surefire/its/RunLastFailedIT.java 
b/surefire-its/src/test/java/org/apache/maven/surefire/its/RunLastFailedIT.java
new file mode 100644
index 000000000..bdddca9c7
--- /dev/null
+++ 
b/surefire-its/src/test/java/org/apache/maven/surefire/its/RunLastFailedIT.java
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.surefire.its;
+
+import org.apache.maven.surefire.its.fixture.OutputValidator;
+import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase;
+import org.apache.maven.surefire.its.fixture.SurefireLauncher;
+import org.apache.maven.surefire.its.fixture.VerificationException;
+import org.junit.jupiter.api.Test;
+
+import static org.hamcrest.Matchers.endsWith;
+import static org.hamcrest.Matchers.is;
+
+/**
+ * Tests {@code runLastFailed}: the second Maven run only runs what failed or 
didn't finish in the first one.
+ * <br>
+ * The project has ATest to ETest, run in that order in one fork. With {@code 
-DfailMe=true}, BTest#fails,
+ * one BTest#squares run and the nested CTest$Inner#innerFails fail. With 
{@code -Dcrash=true}, DCrashTest
+ * kills the fork, so ETest never runs.
+ */
+public class RunLastFailedIT extends SurefireJUnit4IntegrationTestCase {
+
+    @Test
+    public void runsOnlyTheTestsThatFailed() throws VerificationException {
+        SurefireLauncher launcher = unpack("/run-last-failed");
+
+        launcher.setLogFileName("log-first.txt")
+                .addGoal("-DfailMe=true")
+                .addGoal("-Dmaven.test.failure.ignore=true")
+                .executeTest()
+                .assertTestSuiteResults(11, 0, 3, 0);
+
+        launcher.reset();
+        OutputValidator validator = 
launcher.setLogFileName("log-last-failed.txt")
+                .addGoal("-Dsurefire.runLastFailed=true")
+                .maven()
+                .skipClean()
+                .executeTest()
+                .verifyTextInLog("Running only what went wrong last time: 3 
failed test(s).");
+        // BTest#fails, the 3 BTest#squares invocations and 
CTest$Inner#innerFails
+        assertSummary(validator, 5);
+        
validator.getSurefireReportsXmlFile("TEST-lastfailed.BTest.xml").assertContainsText("tests=\"4\"");
+        // ATest didn't run again, its report is still the first one
+        
validator.getSurefireReportsXmlFile("TEST-lastfailed.ATest.xml").assertFileExists();
+
+        launcher.reset();
+        launcher.setLogFileName("log-nothing-left.txt")
+                .addGoal("-Dsurefire.runLastFailed=true")
+                .maven()
+                .skipClean()
+                .executeTest()
+                .verifyTextInLog("No failed or unfinished tests found in")
+                .verifyTextNotInLog("Tests run:");
+    }
+
+    @Test
+    public void runsAllTestsWithoutPreviousReports() throws 
VerificationException {
+        OutputValidator validator = unpack("/run-last-failed")
+                .addGoal("-Dsurefire.runLastFailed=true")
+                .executeTest()
+                .verifyTextInLog("No reports from a previous run in");
+        assertSummary(validator, 11);
+    }
+
+    @Test
+    public void staysInsideTheTestParameter() throws VerificationException {
+        SurefireLauncher launcher = unpack("/run-last-failed");
+
+        launcher.setLogFileName("log-first.txt")
+                .addGoal("-DfailMe=true")
+                .addGoal("-Dmaven.test.failure.ignore=true")
+                .executeTest()
+                .assertTestSuiteResults(11, 0, 3, 0);
+
+        launcher.reset();
+        OutputValidator validator = 
launcher.setLogFileName("log-last-failed.txt")
+                .addGoal("-Dsurefire.runLastFailed=true")
+                .setTestToRun("BTest")
+                .maven()
+                .skipClean()
+                .executeTest()
+                .verifyTextInLog("Running only what went wrong last time: 2 
failed test(s).");
+        // BTest#fails and the 3 BTest#squares invocations, not CTest
+        assertSummary(validator, 4);
+    }
+
+    @Test
+    public void runsTheClassesThatDidNotFinishAfterACrash() throws 
VerificationException {
+        SurefireLauncher launcher = unpack("/run-last-failed");
+
+        launcher.setLogFileName("log-crash.txt")
+                .addGoal("-DfailMe=true")
+                .addGoal("-Dcrash=true")
+                .maven()
+                .failNever()
+                .executeTest()
+                .verifyTextInLog("The forked VM terminated without properly 
saying goodbye")
+                .getTargetFile(".surefire-reports-run-in-progress")
+                .assertFileExists();
+
+        launcher.reset();
+        OutputValidator validator = 
launcher.setLogFileName("log-last-failed.txt")
+                .addGoal("-Dsurefire.runLastFailed=true")
+                .maven()
+                .skipClean()
+                .executeTest()
+                .verifyTextInLog("Running only what went wrong last time: 3 
failed test(s), "
+                        + "2 class(es) that didn't finish.");
+        // the 5 failed tests of BTest and CTest, then DCrashTest and ETest
+        assertSummary(validator, 7);
+        
validator.getSurefireReportsXmlFile("TEST-lastfailed.ETest.xml").assertFileExists();
+        
validator.getTargetFile(".surefire-reports-run-in-progress").assertFileNotExists();
+    }
+
+    @Test
+    public void failsafeRunsOnlyTheTestsThatFailed() throws 
VerificationException {
+        SurefireLauncher launcher = unpack("/run-last-failed");
+
+        launcher.setLogFileName("log-first.txt")
+                .addGoal("-DfailMe=true")
+                .addGoal("-Dmaven.test.failure.ignore=true")
+                .executeVerify()
+                .assertIntegrationTestSuiteResults(2, 0, 1, 0);
+
+        launcher.reset();
+        // failures aren't ignored now, so a passing verify means the old 
summary was replaced
+        launcher.setLogFileName("log-last-failed.txt")
+                .addGoal("-Dsurefire.runLastFailed=true")
+                .addGoal("-Dfailsafe.runLastFailed=true")
+                .maven()
+                .skipClean()
+                .executeVerify()
+                .verifyTextInLog("Running only what went wrong last time: 1 
failed test(s).")
+                .getTargetFile("failsafe-reports/TEST-lastfailed.FooIT.xml")
+                .assertContainsText("tests=\"1\"");
+    }
+
+    /**
+     * Checks the final "Tests run" line, not the per class ones.
+     */
+    private static void assertSummary(OutputValidator validator, int total) 
throws VerificationException {
+        validator.assertThatLogLine(endsWith("Tests run: " + total + ", 
Failures: 0, Errors: 0, Skipped: 0"), is(1));
+    }
+}
diff --git a/surefire-its/src/test/resources/run-last-failed/pom.xml 
b/surefire-its/src/test/resources/run-last-failed/pom.xml
new file mode 100644
index 000000000..09dd21a54
--- /dev/null
+++ b/surefire-its/src/test/resources/run-last-failed/pom.xml
@@ -0,0 +1,80 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements.  See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership.  The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License.  You may obtain a copy of the License at
+  ~
+  ~     http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied.  See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.plugins.surefire</groupId>
+  <artifactId>run-last-failed</artifactId>
+  <version>1.0-SNAPSHOT</version>
+  <name>Test for runLastFailed</name>
+
+  <properties>
+    <maven.compiler.source>1.8</maven.compiler.source>
+    <maven.compiler.target>1.8</maven.compiler.target>
+    <junit.version>5.14.1</junit.version>
+  </properties>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-api</artifactId>
+      <version>${junit.version}</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-params</artifactId>
+      <version>${junit.version}</version>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-surefire-plugin</artifactId>
+        <version>${surefire.version}</version>
+        <configuration>
+          <!-- one fork, classes in a fixed order: a crash in DCrashTest means 
ETest never runs -->
+          <forkCount>1</forkCount>
+          <reuseForks>true</reuseForks>
+          <runOrder>alphabetical</runOrder>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-failsafe-plugin</artifactId>
+        <version>${surefire.version}</version>
+        <executions>
+          <execution>
+            <goals>
+              <goal>integration-test</goal>
+              <goal>verify</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+
+</project>
diff --git 
a/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/ATest.java
 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/ATest.java
new file mode 100644
index 000000000..60c3f883c
--- /dev/null
+++ 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/ATest.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package lastfailed;
+
+import org.junit.jupiter.api.Test;
+
+public class ATest {
+    @Test
+    public void passes() {}
+}
diff --git 
a/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/BTest.java
 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/BTest.java
new file mode 100644
index 000000000..98bafacda
--- /dev/null
+++ 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/BTest.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package lastfailed;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class BTest {
+    @Test
+    public void passes() {}
+
+    @Test
+    public void fails() {
+        assertTrue(!Boolean.getBoolean("failMe"), "failMe is set");
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {1, 2, 3})
+    public void squares(int value) {
+        if (Boolean.getBoolean("failMe")) {
+            assertNotEquals(2, value);
+        }
+    }
+}
diff --git 
a/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/CTest.java
 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/CTest.java
new file mode 100644
index 000000000..d6a127d7c
--- /dev/null
+++ 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/CTest.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package lastfailed;
+
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class CTest {
+    @Test
+    public void passes() {}
+
+    @Nested
+    class Inner {
+        @Test
+        public void innerPasses() {}
+
+        @Test
+        public void innerFails() {
+            assertTrue(!Boolean.getBoolean("failMe"), "failMe is set");
+        }
+    }
+}
diff --git 
a/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/DCrashTest.java
 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/DCrashTest.java
new file mode 100644
index 000000000..530dff272
--- /dev/null
+++ 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/DCrashTest.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package lastfailed;
+
+import org.junit.jupiter.api.Test;
+
+public class DCrashTest {
+    @Test
+    public void crashes() {
+        if (Boolean.getBoolean("crash")) {
+            // kills the forked JVM, like a real crash
+            Runtime.getRuntime().halt(1);
+        }
+    }
+}
diff --git 
a/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/ETest.java
 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/ETest.java
new file mode 100644
index 000000000..e4a4d686f
--- /dev/null
+++ 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/ETest.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package lastfailed;
+
+import org.junit.jupiter.api.Test;
+
+public class ETest {
+    @Test
+    public void passes() {}
+}
diff --git 
a/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/FooIT.java
 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/FooIT.java
new file mode 100644
index 000000000..3473f5fd5
--- /dev/null
+++ 
b/surefire-its/src/test/resources/run-last-failed/src/test/java/lastfailed/FooIT.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package lastfailed;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class FooIT {
+    @Test
+    public void passes() {}
+
+    @Test
+    public void fails() {
+        assertTrue(!Boolean.getBoolean("failMe"), "failMe is set");
+    }
+}

Reply via email to