Top Description Inners Fields Constructors Methods
org.assertj.core.api.junit.jupiter

public Class SoftAssertionsExtension

extends Object
implements TestInstancePostProcessor, BeforeEachCallback, ParameterResolver, AfterTestExecutionCallback
Class Inheritance
All Implemented Interfaces
org.junit.jupiter.api.extension.AfterTestExecutionCallback, org.junit.jupiter.api.extension.Extension, org.junit.jupiter.api.extension.ParameterResolver, org.junit.jupiter.api.extension.BeforeEachCallback, org.junit.jupiter.api.extension.TestInstancePostProcessor
Static Imports
java.lang.String.format, java.lang.reflect.Modifier.isAbstract, org.junit.platform.commons.support.AnnotationSupport.findAnnotation, .AnnotationSupport.isAnnotated, .ReflectionSupport.findFields

Extension for JUnit Jupiter that provides support for injecting a concrete implementation of SoftAssertionsProvider into test methods and (since 3.18.0) into test fields annotated with @InjectSoftAssertions.

Two examples of SoftAssertionsProviders that come packaged with AssertJ are SoftAssertions and BDDSoftAssertions, but custom implementations are also supported as long as they are non-abstract and have a default constructor.

Applicability

In this context, the term "test method" refers to any method annotated with @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, or @TestTemplate.
This extension does not inject SoftAssertionsProvider arguments into test constructors or lifecycle methods.

Scope

Annotated SoftAssertionsProvider fields become valid from the `@BeforeEach` lifecycle phase. For parameters, they become are valid when the parameter is resolved.
In the afterTestExecution phase (immediately after the test has returned, but before the AfterEach phase, all collected errors (if any) will wrapped in a single multiple-failures error.
All SoftAssertionsProvider instances (fields & parameters) created within the scope of the same test method (including its BeforeEach phase) will share the same state object to collect the failed assertions, so that all assertion failures from all SoftAssertionsProviders will be reported in the order that they failed.

Integration with third-party extensions

Sometimes a third-party extension may wish to softly assert something as part of the main test. Or sometimes a third-party extension may be a wrapper around another assertion library (eg, Mockito) and it would be nice for that library's soft assertions to mix well with AssertJ's. This can be achieved through the use of the SoftAssertionExtension's API. Calling getAssertionErrorCollector(ExtensionContext) will return a handle to the error collector used for the current context into which a third-party extension can directly store its assertion failures. Alternatively, calling getSoftAssertionsProvider() will instantiate a SoftAssertionsProvider for the given context that can then be used to make assertions.

Examples

Example parameter injection

 @ExtendWith(SoftAssertionsExtension.class)
class ExampleTestCase {

   @InjectSoftAssertions
   BDDSoftAssertions bdd;

   @Test
   void multipleFailures(SoftAssertions softly) {
      softly.assertThat(2 * 3).isEqualTo(0);
      softly.assertThat(Arrays.asList(1, 2)).containsOnly(1);
      softly.assertThat(1 + 1).isEqualTo(2);
   }
}

Example field injection

 @ExtendWith(SoftlyExtension.class)
public class SoftlyExtensionExample {

  // initialized by the SoftlyExtension extension
  @InjectSoftAssertions
  private SoftAssertions soft;

  @Test
  public void chained_soft_assertions_example() {
    String name = "Michael Jordan - Bulls";
    soft.assertThat(name)
        .startsWith("Mi")
        .contains("Bulls");
    // no need to call softly.assertAll(), this is done by the extension
  }

  // nested classes test work too
  @Nested
  class NestedExample {

    @Test
    public void football_assertions_example() {
      String kylian = "Kylian Mbappé";
      soft.assertThat(kylian)
          .startsWith("Ky")
          .contains("bap");
      // no need to call softly.assertAll(), this is done by the extension
    }
  }
} 

Example using a mix of field and parameter injection

 @ExtendWith(SoftAssertionsExtension.class)
class ExampleTestCase {

   @InjectSoftAssertions
   SoftAssertions softly

   @Test
   void multipleFailures(BDDSoftAssertions bdd) {
      bdd.then(2 * 3).isEqualTo(0);
      softly.assertThat(Arrays.asList(1, 2)).containsOnly(1);
      bdd.then(1 + 1).isEqualTo(2);
      // When SoftAssertionsExtension calls assertAll(), the three
      // above failures above will be reported in-order.
   }
}

Example third-party extension using SoftAssertionsExtension


class ExampleTestCase implements BeforeEachCallback {

   @Override
   public void beforeEach(ExtensionContext context) {
     SoftAssertions softly = SoftAssertionsExtension
       .getSoftAssertionsProvider(context, SoftAssertions.class);
     softly.assertThat(false).isTrue();
     // When SoftAssertionsExtension calls assertAll(), the
     // above failure will be included in the list of reported failures.
   }
}
Authors
Sam Brannen, Arthur Mita (author of SoftlyExtension), Fr Jeremy Krieg
Since
3.13

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class

Field Summary

Modifier and TypeField and Description
private static final ExtensionContext.Namespace

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
afterTestExecution(ExtensionContext
the current extension context; never null
extensionContext
)

Implements org.junit.jupiter.api.extension.AfterTestExecutionCallback.afterTestExecution.

Callback that is invoked immediately after an individual test has been executed but before any user-defined teardown methods have been executed for that test.
private static Class<? extends SoftAssertionsProvider>
asSoftAssertionsProviderClass(Field softAssertionsField, Class<?> providerClass)

public void
beforeEach(ExtensionContext
the current extension context; never null
context
)

Implements org.junit.jupiter.api.extension.BeforeEachCallback.beforeEach.

Callback that is invoked before an individual test and any user-defined setup methods for that test have been executed.
private static void
checkHasDefaultConstructor(Field softAssertionsField, Class<? extends SoftAssertionsProvider> softAssertionsProviderClass)

private static void
checkIsNotAbstract(Field softAssertionsField, Class<? extends SoftAssertionsProvider> softAssertionsProviderClass)

private static void
checkIsNotStaticOrFinal(Field softAssertionsField)

public static AssertionErrorCollector

Returns:

The AssertionErrorCollector for the given context.
getAssertionErrorCollector
(ExtensionContext
the ExtensionContext whose error collector we are attempting to retrieve.
context
)

Returns the AssertionErrorCollector for the given extension context, if none exists for the current context then one is created.

public static <
the type of SoftAssertionsProvider to instantiate.
T extends SoftAssertionsProvider
>
T

Returns:

The AssertionErrorCollector for the given context.
getSoftAssertionsProvider
(ExtensionContext
the ExtensionContext whose error collector we are attempting to retrieve.
context
,
Class<T>
the class instance for the type of soft assertions
concreteSoftAssertionsProviderType
)

Returns a SoftAssertionsProvider instance of the given type for the given extension context.

private static Collection<SoftAssertionsProvider>
private static ExtensionContext.Store
getStore(ExtensionContext extensionContext)

private static SoftAssertionsExtension.ThreadLocalErrorCollector
private static boolean
private static <T extends SoftAssertionsProvider> T
instantiateProvider(ExtensionContext context, Class<T> providerType)

pack-priv static boolean
pack-priv static boolean
pack-priv static boolean
private static boolean
public void
postProcessTestInstance(Object
the instance to post-process; never null
testInstance
,
ExtensionContext
the current extension context; never null
context
)

Implements org.junit.jupiter.api.extension.TestInstancePostProcessor.postProcessTestInstance.

Callback for post-processing the supplied test instance.
public Object
resolveParameter(ParameterContext
the context for the parameter for which an argument should be resolved; never null
parameterContext
,
ExtensionContext
the extension context for the Executable about to be invoked; never null
extensionContext
)

Implements org.junit.jupiter.api.extension.ParameterResolver.resolveParameter.

Resolve an argument for the Parameter in the supplied ParameterContext for the supplied ExtensionContext.
private static void
setTestInstanceSoftAssertionsField(Object testInstance, Field softAssertionsField, SoftAssertionsProvider softAssertions)

public boolean
supportsParameter(ParameterContext
the context for the parameter for which an argument should be resolved; never null
parameterContext
,
ExtensionContext
the extension context for the Executable about to be invoked; never null
extensionContext
)

Implements org.junit.jupiter.api.extension.ParameterResolver.supportsParameter.

Determine if this resolver supports resolution of an argument for the Parameter in the supplied ParameterContext for the supplied ExtensionContext.
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

SOFT_ASSERTIONS_EXTENSION_NAMESPACEback to summary
private static final ExtensionContext.Namespace SOFT_ASSERTIONS_EXTENSION_NAMESPACE

Constructor Detail

SoftAssertionsExtensionback to summary
public SoftAssertionsExtension()

Method Detail

afterTestExecutionback to summary
public void afterTestExecution(ExtensionContext extensionContext)

Implements org.junit.jupiter.api.extension.AfterTestExecutionCallback.afterTestExecution.

Doc from org.junit.jupiter.api.extension.AfterTestExecutionCallback.afterTestExecution.

Callback that is invoked immediately after an individual test has been executed but before any user-defined teardown methods have been executed for that test.

Parameters
extensionContext:ExtensionContext

the current extension context; never null

Annotations
@Override
asSoftAssertionsProviderClassback to summary
private static Class<? extends SoftAssertionsProvider> asSoftAssertionsProviderClass(Field softAssertionsField, Class<?> providerClass)
Annotations
@SuppressWarnings:unchecked
beforeEachback to summary
public void beforeEach(ExtensionContext context) throws Exception

Implements org.junit.jupiter.api.extension.BeforeEachCallback.beforeEach.

Doc from org.junit.jupiter.api.extension.BeforeEachCallback.beforeEach.

Callback that is invoked before an individual test and any user-defined setup methods for that test have been executed.

Parameters
context:ExtensionContext

the current extension context; never null

Annotations
@Override
checkHasDefaultConstructorback to summary
private static void checkHasDefaultConstructor(Field softAssertionsField, Class<? extends SoftAssertionsProvider> softAssertionsProviderClass)
checkIsNotAbstractback to summary
private static void checkIsNotAbstract(Field softAssertionsField, Class<? extends SoftAssertionsProvider> softAssertionsProviderClass)
checkIsNotStaticOrFinalback to summary
private static void checkIsNotStaticOrFinal(Field softAssertionsField)
getAssertionErrorCollectorback to summary
public static AssertionErrorCollector getAssertionErrorCollector(ExtensionContext context)

Returns the AssertionErrorCollector for the given extension context, if none exists for the current context then one is created.

This method is thread safe - all extensions attempting to access the AssertionErrorCollector for a given context through this method will get a reference to the same AssertionErrorCollector instance, regardless of the order in which they are called.

Third-party extensions that wish to provide soft-asserting behavior can use this method to obtain the current AssertionErrorCollector instance and record their assertion failures into it by calling collectAssertionError(AssertionError).
In this way their soft assertions will integrate with the existing AssertJ soft assertions and the assertion failures (both AssertJ's and the third-party extension's) will be reported in the order that they occurred.

Parameters
context:ExtensionContext

the ExtensionContext whose error collector we are attempting to retrieve.

Returns:AssertionErrorCollector

The AssertionErrorCollector for the given context.

Annotations
@Beta
getSoftAssertionsProviderback to summary
public static <T extends SoftAssertionsProvider> T getSoftAssertionsProvider(ExtensionContext context, Class<T> concreteSoftAssertionsProviderType)

Returns a SoftAssertionsProvider instance of the given type for the given extension context. If no instance of the given type exists for the supplied context, then one is created.
Note that the given type must be a concrete type with an accessible no-arg constructor for this method to work.

This method is thread safe - all extensions attempting to access the SoftAssertionsProvider for a given context through this method will receive end up getting a reference to the same SoftAssertionsProvider instance of that same type, regardless of the order in which they are called.

Third party extensions that wish to use soft assertions in their own implementation can use this to get a SoftAssertionsProvider instance that interoperates with other soft-asserting extensions (including SoftAssertionsExtension).

The SoftAssertionExtension will take care of initialising this provider instance's delegate at the appropriate time, so that collected soft assertions are routed to the AssertionErrorCollector instance for the current context.

 public class CustomExtension implements BeforeEachCallback {

  @Override
  public void beforeEach(ExtensionContext context) {
    CustomSoftAssertions softly = SoftAssertionsExtension.getSoftAssertionsProvider(context, CustomSoftAssertions.class);
    softly.assertThat(1).isOne();
  }
}
Parameters
<T>
the type of SoftAssertionsProvider to instantiate.
context:ExtensionContext

the ExtensionContext whose error collector we are attempting to retrieve.

concreteSoftAssertionsProviderType:Class<T>

the class instance for the type of soft assertions

Returns:T

The AssertionErrorCollector for the given context.

Annotations
@Beta
getSoftAssertionsProvidersback to summary
private static Collection<SoftAssertionsProvider> getSoftAssertionsProviders(ExtensionContext context)
Annotations
@SuppressWarnings:unchecked
getStoreback to summary
private static ExtensionContext.Store getStore(ExtensionContext extensionContext)
getThreadLocalCollectorback to summary
private static SoftAssertionsExtension.ThreadLocalErrorCollector getThreadLocalCollector(ExtensionContext context)
initialiseDelegateback to summary
private static boolean initialiseDelegate(ExtensionContext context, AssertionErrorCollector collector)
instantiateProviderback to summary
private static <T extends SoftAssertionsProvider> T instantiateProvider(ExtensionContext context, Class<T> providerType)
isAnnotatedConcurrentback to summary
pack-priv static boolean isAnnotatedConcurrent(ExtensionContext context)
isPerClassback to summary
pack-priv static boolean isPerClass(ExtensionContext context)
isPerClassConcurrentback to summary
pack-priv static boolean isPerClassConcurrent(ExtensionContext context)
isUnsupportedParameterTypeback to summary
private static boolean isUnsupportedParameterType(Parameter parameter)
postProcessTestInstanceback to summary
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception

Implements org.junit.jupiter.api.extension.TestInstancePostProcessor.postProcessTestInstance.

Doc from org.junit.jupiter.api.extension.TestInstancePostProcessor.postProcessTestInstance.

Callback for post-processing the supplied test instance.

Note

the ExtensionContext supplied to a TestInstancePostProcessor will always return an empty java.util.Optional value from getTestInstance(). A TestInstancePostProcessor should therefore only attempt to process the supplied testInstance.

Parameters
testInstance:Object

the instance to post-process; never null

context:ExtensionContext

the current extension context; never null

Annotations
@Override
resolveParameterback to summary
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)

Implements org.junit.jupiter.api.extension.ParameterResolver.resolveParameter.

Doc from org.junit.jupiter.api.extension.ParameterResolver.resolveParameter.

Resolve an argument for the Parameter in the supplied ParameterContext for the supplied ExtensionContext.

This method is only called by the framework if supportsParameter previously returned true for the same ParameterContext and ExtensionContext.

The java.lang.reflect.Method or java.lang.reflect.Constructor in which the parameter is declared can be retrieved via ParameterContext#getDeclaringExecutable().

Parameters
parameterContext:ParameterContext

the context for the parameter for which an argument should be resolved; never null

extensionContext:ExtensionContext

the extension context for the Executable about to be invoked; never null

Returns:Object

the resolved argument for the parameter; may only be null if the parameter type is not a primitive

Annotations
@Override
setTestInstanceSoftAssertionsFieldback to summary
private static void setTestInstanceSoftAssertionsField(Object testInstance, Field softAssertionsField, SoftAssertionsProvider softAssertions)
supportsParameterback to summary
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)

Implements org.junit.jupiter.api.extension.ParameterResolver.supportsParameter.

Doc from org.junit.jupiter.api.extension.ParameterResolver.supportsParameter.

Determine if this resolver supports resolution of an argument for the Parameter in the supplied ParameterContext for the supplied ExtensionContext.

The java.lang.reflect.Method or java.lang.reflect.Constructor in which the parameter is declared can be retrieved via ParameterContext#getDeclaringExecutable().

Parameters
parameterContext:ParameterContext

the context for the parameter for which an argument should be resolved; never null

extensionContext:ExtensionContext

the extension context for the Executable about to be invoked; never null

Returns:boolean

true if this resolver can resolve an argument for the parameter

Annotations
@Override
org.assertj.core.api.junit.jupiter back to summary

pack-priv Class SoftAssertionsExtension.ThreadLocalErrorCollector

extends Object
implements AssertionErrorCollector
Class Inheritance
  • java.lang.Object
  • org.assertj.core.api.junit.jupiter.SoftAssertionsExtension.ThreadLocalErrorCollector
All Implemented Interfaces
org.assertj.core.api.AssertionErrorCollector, org.assertj.core.api.AfterAssertionErrorCollected

Field Summary

Modifier and TypeField and Description
pack-priv InheritableThreadLocal<AssertionErrorCollector>

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public List<AssertionError>
public void
collectAssertionError(AssertionError
the AssertionError to collect.
assertionError
)

Implements org.assertj.core.api.AssertionErrorCollector.collectAssertionError.

This method can be used to collect soft assertion errors.
public Optional<AssertionErrorCollector>
public void
public void
setDelegate(AssertionErrorCollector
the AssertionErrorCollector to which the assertions will be forwarded.
assertionErrorCollector
)

Overrides default org.assertj.core.api.AssertionErrorCollector.setDelegate.

Optionally sets a "delegate" collector into which the collected assertions will be deposited.
public void
succeeded()

Implements org.assertj.core.api.AssertionErrorCollector.succeeded.

Indicates/sets that the last assertion was a success.
public boolean
wasSuccess()

Implements org.assertj.core.api.AssertionErrorCollector.wasSuccess.

Returns the result of last soft assertion which can be used to decide what the next one should be.
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

threadLocalback to summary
pack-priv InheritableThreadLocal<AssertionErrorCollector> threadLocal

Constructor Detail

ThreadLocalErrorCollectorback to summary
pack-priv ThreadLocalErrorCollector()

Method Detail

assertionErrorsCollectedback to summary
public List<AssertionError> assertionErrorsCollected()

Implements org.assertj.core.api.AssertionErrorCollector.assertionErrorsCollected.

Annotations
@Override
collectAssertionErrorback to summary
public void collectAssertionError(AssertionError assertionError)

Implements org.assertj.core.api.AssertionErrorCollector.collectAssertionError.

Doc from org.assertj.core.api.AssertionErrorCollector.collectAssertionError.

This method can be used to collect soft assertion errors.

To be able to react after an assertion error is collected, use onAssertionErrorCollected(AssertionError).

Parameters
assertionError:AssertionError

the AssertionError to collect.

Annotations
@Override
getDelegateback to summary
public Optional<AssertionErrorCollector> getDelegate()

Overrides default org.assertj.core.api.AssertionErrorCollector.getDelegate.

Annotations
@Override
resetback to summary
public void reset()
setDelegateback to summary
public void setDelegate(AssertionErrorCollector assertionErrorCollector)

Overrides default org.assertj.core.api.AssertionErrorCollector.setDelegate.

Doc from org.assertj.core.api.AssertionErrorCollector.setDelegate.

Optionally sets a "delegate" collector into which the collected assertions will be deposited.

Note that if you set a delegate, this instance will no longer collect or report assertion errors itself but will forward them all to the delegate for collection.

Parameters
assertionErrorCollector:AssertionErrorCollector

the AssertionErrorCollector to which the assertions will be forwarded.

Annotations
@Override
succeededback to summary
public void succeeded()

Implements org.assertj.core.api.AssertionErrorCollector.succeeded.

Doc from org.assertj.core.api.AssertionErrorCollector.succeeded.

Indicates/sets that the last assertion was a success.

Annotations
@Override
wasSuccessback to summary
public boolean wasSuccess()

Implements org.assertj.core.api.AssertionErrorCollector.wasSuccess.

Doc from org.assertj.core.api.AssertionErrorCollector.wasSuccess.

Returns the result of last soft assertion which can be used to decide what the next one should be.

Example:

 Person person = ...
SoftAssertions soft = new SoftAssertions();
if (soft.assertThat(person.getAddress()).isNotNull().wasSuccess()) {
    soft.assertThat(person.getAddress().getStreet()).isNotNull();
}
Returns:boolean

true if the last assertion was a success.

Annotations
@Override