assertj / assertj-swing

Fluent assertions for Swing apps
Other
108 stars 52 forks source link

Support for JUnit 5 #259

Open LorenzoBettini opened 3 years ago

LorenzoBettini commented 3 years ago

Hi

is there any plan to provide something similar to the GUITestRunner and AssertJSwingJUnitTestCase for JUnit 5? I guess that the corresponding mechanism of GUITestRunner would be a Jupiter extension?

wjbakker commented 3 years ago

Hi @LorenzoBettini ,

You can define a GUITestExtension as following:

import org.assertj.swing.junit.runner.FailureScreenshotTaker;
import org.assertj.swing.junit.runner.ImageFolderCreator;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;

import java.lang.reflect.Method;

import static org.assertj.swing.annotation.GUITestFinder.isGUITest;
import static org.assertj.swing.junit.runner.Formatter.testNameFrom;

/**
 * Understands a JUnit 5 extension that takes a screenshot of a failed GUI test.
 * The Junit 4 runner is available in {@link org.assertj.swing.junit.runner.GUITestRunner}.
 *
 * @see <a href="https://github.com/assertj/assertj-swing/issues/259">assertj-swing #259</a>
 * @author William Bakker
 */
public class GUITestExtension implements Extension, InvocationInterceptor {
    private final FailureScreenshotTaker screenshotTaker;

    public GUITestExtension() {
        screenshotTaker = new FailureScreenshotTaker(new ImageFolderCreator().createImageFolder());
    }

    @Override
    public void interceptTestMethod(
            Invocation<Void> invocation,
            ReflectiveInvocationContext<Method> invocationContext,
            ExtensionContext extensionContext) 
            throws Throwable {
        try {
            invocation.proceed();
        } catch (Throwable t) {
            takeScreenshot(invocationContext.getExecutable());
            throw t;
        }
    }

    private void takeScreenshot(Method method) {
        final Class<?> testClass = method.getDeclaringClass();
        if (!(isGUITest(testClass, method)))
            return;
        screenshotTaker.saveScreenshot(testNameFrom(testClass, method));
    }
}
hakanai commented 3 years ago

Ah, that is interesting. We had made our own JUnit 5 extension for AssertJ-Swing but we didn't even think of putting in a screenshot taker, all ours does is spin up the Robot and tear it down at the end.

scordio commented 2 years ago

Unfortunately, the project lead no longer has time for AssertJ Swing and we are looking for committers (see #264).

Also, @wjbakker @hakanai in case your work could be generally usable, feel free to raise a PR and we will do our best to get it merged.