How to use setTestInstanceSoftAssertionsField method of org.assertj.core.api.junit.jupiter.SoftAssertionsExtension class

Best Assertj code snippet using org.assertj.core.api.junit.jupiter.SoftAssertionsExtension.setTestInstanceSoftAssertionsField

Source:SoftAssertionsExtension.java Github

copy

Full Screen

...233 softAssertionsField.getType());234 checkIsNotAbstract(softAssertionsField, softAssertionsProviderClass);235 checkHasDefaultConstructor(softAssertionsField, softAssertionsProviderClass);236 SoftAssertionsProvider softAssertions = getSoftAssertionsProvider(context, softAssertionsProviderClass);237 setTestInstanceSoftAssertionsField(testInstance, softAssertionsField, softAssertions);238 }239 }240 @Override241 public void beforeEach(ExtensionContext context) throws Exception {242 AssertionErrorCollector collector = getAssertionErrorCollector(context);243 if (isPerClassConcurrent(context)) {244 // If the current context is "per class+concurrent", then getSoftAssertionsProvider() will have already set the delegate245 // for all the soft assertions provider to the thread-local error collector, so all we need to do is set the tlec's value246 // for the current thread.247 ThreadLocalErrorCollector tlec = getThreadLocalCollector(context);248 tlec.setDelegate(collector);249 } else {250 // Make sure that all of the soft assertion provider instances have their delegate initialised to the assertion error251 // collector for the current context. Also check enclosing contexts (in the case of nested tests).252 while (initialiseDelegate(context, collector) && context.getParent().isPresent()) {253 context = context.getParent().get();254 }255 }256 }257 private static boolean initialiseDelegate(ExtensionContext context, AssertionErrorCollector collector) {258 Collection<SoftAssertionsProvider> providers = getSoftAssertionsProviders(context);259 if (providers == null) return false;260 providers.forEach(x -> x.setDelegate(collector));261 return context.getParent().isPresent();262 }263 @Override264 public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {265 // Abort if parameter type is unsupported.266 if (isUnsupportedParameterType(parameterContext.getParameter())) return false;267 Executable executable = parameterContext.getDeclaringExecutable();268 // @Testable is used as a meta-annotation on @Test, @TestFactory, @TestTemplate, etc.269 boolean isTestableMethod = executable instanceof Method && isAnnotated(executable, Testable.class);270 if (!isTestableMethod) {271 throw new ParameterResolutionException(format("Configuration error: cannot resolve SoftAssertionsProvider instances for [%s]. Only test methods are supported.",272 executable));273 }274 Class<?> parameterType = parameterContext.getParameter().getType();275 if (isAbstract(parameterType.getModifiers())) {276 throw new ParameterResolutionException(format("Configuration error: the resolved SoftAssertionsProvider implementation [%s] is abstract and cannot be instantiated.",277 executable));278 }279 try {280 parameterType.getDeclaredConstructor();281 } catch (@SuppressWarnings("unused") Exception e) {282 throw new ParameterResolutionException(format("Configuration error: the resolved SoftAssertionsProvider implementation [%s] has no default constructor and cannot be instantiated.",283 executable));284 }285 return true;286 }287 @Override288 public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {289 // The parameter type is guaranteed to be an instance of SoftAssertionsProvider290 @SuppressWarnings("unchecked")291 Class<? extends SoftAssertionsProvider> concreteSoftAssertionsProviderType = (Class<? extends SoftAssertionsProvider>) parameterContext.getParameter()292 .getType();293 SoftAssertionsProvider provider = ReflectionSupport.newInstance(concreteSoftAssertionsProviderType);294 provider.setDelegate(getAssertionErrorCollector(extensionContext));295 return provider;296 }297 @Override298 public void afterTestExecution(ExtensionContext extensionContext) {299 AssertionErrorCollector collector;300 if (isPerClassConcurrent(extensionContext)) {301 ThreadLocalErrorCollector tlec = getThreadLocalCollector(extensionContext);302 collector = tlec.getDelegate().orElseThrow(() -> new IllegalStateException("Expecting delegate to be present for current context"));303 tlec.reset();304 } else {305 collector = getAssertionErrorCollector(extensionContext);306 }307 AbstractSoftAssertions.assertAll(collector);308 }309 private static boolean isUnsupportedParameterType(Parameter parameter) {310 Class<?> type = parameter.getType();311 return !SoftAssertionsProvider.class.isAssignableFrom(type);312 }313 private static Store getStore(ExtensionContext extensionContext) {314 return extensionContext.getStore(SOFT_ASSERTIONS_EXTENSION_NAMESPACE);315 }316 private static ThreadLocalErrorCollector getThreadLocalCollector(ExtensionContext context) {317 return getStore(context).getOrComputeIfAbsent(ThreadLocalErrorCollector.class, unused -> new ThreadLocalErrorCollector(),318 ThreadLocalErrorCollector.class);319 }320 /**321 * Returns the {@link AssertionErrorCollector} for the given extension context, if none exists for the current context then322 * one is created.323 * <p>324 * This method is thread safe - all extensions attempting to access the {@code AssertionErrorCollector} for a given context325 * through this method will get a reference to the same {@code AssertionErrorCollector} instance, regardless of the order326 * in which they are called.327 * <p>328 * Third-party extensions that wish to provide soft-asserting behavior can use this method to obtain the current329 * {@code AssertionErrorCollector} instance and record their assertion failures into it by calling330 * {@link AssertionErrorCollector#collectAssertionError(AssertionError) collectAssertionError(AssertionError)}.<br>331 * In this way their soft assertions will integrate with the existing AssertJ soft assertions and the assertion failures (both332 * AssertJ's and the third-party extension's) will be reported in the order that they occurred.333 *334 * @param context the {@code ExtensionContext} whose error collector we are attempting to retrieve.335 * @return The {@code AssertionErrorCollector} for the given context.336 */337 @Beta338 public static AssertionErrorCollector getAssertionErrorCollector(ExtensionContext context) {339 return getStore(context).getOrComputeIfAbsent(AssertionErrorCollector.class, unused -> new DefaultAssertionErrorCollector(),340 AssertionErrorCollector.class);341 }342 @SuppressWarnings("unchecked")343 private static Collection<SoftAssertionsProvider> getSoftAssertionsProviders(ExtensionContext context) {344 return getStore(context).getOrComputeIfAbsent(Collection.class, unused -> new ConcurrentLinkedQueue<>(), Collection.class);345 }346 private static <T extends SoftAssertionsProvider> T instantiateProvider(ExtensionContext context, Class<T> providerType) {347 T softAssertions = ReflectionSupport.newInstance(providerType);348 // If we are running single-threaded, we won't have any concurrency issues. Likewise,349 // if we are running "per-method", then every test gets its own instance and again there350 // won't be any concurrency issues. But we need to special-case the situation where351 // we are running *both* per class and concurrent - use a thread-local so that each thread352 // gets its own copy. The beforeEach() callback above will take care of setting the353 // ThreadLocal collector's value for the thread in which it is executing.354 if (isPerClassConcurrent(context)) {355 softAssertions.setDelegate(getThreadLocalCollector(context));356 } else if (context.getTestMethod().isPresent()) {357 // If we're already in a method, then set our delegate as the beforeEach() which sets it may have already run.358 softAssertions.setDelegate(getAssertionErrorCollector(context));359 }360 getSoftAssertionsProviders(context).add(softAssertions);361 return softAssertions;362 }363 /**364 * Returns a {@link SoftAssertionsProvider} instance of the given type for the given extension context.365 * If no instance of the given type exists for the supplied context, then one is created.<br>366 * Note that the given type must be a concrete type with an accessible no-arg constructor for this method to work.367 * <p>368 * This method is thread safe - all extensions attempting to access the {@code SoftAssertionsProvider} for a369 * given context through this method will receive end up getting a reference to the same370 * {@code SoftAssertionsProvider} instance of that same type, regardless of the order in which they are called.371 * <p>372 * Third party extensions that wish to use soft assertions in their own implementation can use this373 * to get a {@code SoftAssertionsProvider} instance that interoperates with other soft-asserting374 * extensions (including {@code SoftAssertionsExtension}).375 * <p>376 * The {@code SoftAssertionExtension} will take care of initialising this provider instance's delegate377 * at the appropriate time, so that collected soft assertions are routed to the {@link AssertionErrorCollector}378 * instance for the current context.379 *380 * <pre><code class='java'> public class CustomExtension implements BeforeEachCallback {381 *382 * {@literal @}Override383 * public void beforeEach(ExtensionContext context) {384 * CustomSoftAssertions softly = SoftAssertionsExtension.getSoftAssertionsProvider(context, CustomSoftAssertions.class);385 * softly.assertThat(1).isOne();386 * }387 * }</code>388 * </pre>389 *390 * @param <T> the type of {@link SoftAssertionsProvider} to instantiate.391 * @param context the {@code ExtensionContext} whose error collector we are attempting to retrieve.392 * @param concreteSoftAssertionsProviderType the class instance for the type of soft assertions393 * @return The {@code AssertionErrorCollector} for the given context.394 */395 @Beta396 public static <T extends SoftAssertionsProvider> T getSoftAssertionsProvider(ExtensionContext context,397 Class<T> concreteSoftAssertionsProviderType) {398 return getStore(context).getOrComputeIfAbsent(concreteSoftAssertionsProviderType,399 unused -> instantiateProvider(context, concreteSoftAssertionsProviderType),400 concreteSoftAssertionsProviderType);401 }402 private static void setTestInstanceSoftAssertionsField(Object testInstance, Field softAssertionsField,403 SoftAssertionsProvider softAssertions) {404 softAssertionsField.setAccessible(true);405 try {406 softAssertionsField.set(testInstance, softAssertions);407 } catch (IllegalAccessException e) {408 throw new ExtensionConfigurationException(format("[%s] Could not gain access to field", softAssertionsField.getName()), e);409 }410 }411 private static void checkHasDefaultConstructor(Field softAssertionsField,412 Class<? extends SoftAssertionsProvider> softAssertionsProviderClass) {413 try {414 softAssertionsProviderClass.getDeclaredConstructor();415 } catch (@SuppressWarnings("unused") Exception e) {416 throw new ExtensionConfigurationException(format("[%s] SoftAssertionsProvider [%s] does not have a default constructor",...

Full Screen

Full Screen

setTestInstanceSoftAssertionsField

Using AI Code Generation

copy

Full Screen

1SoftAssertions softly = new SoftAssertions();2SoftAssertionsExtension.setTestInstanceSoftAssertionsField(testInfo, softly);3public class SoftAssertionsExtensionJUnit4 implements TestRule {4 private final SoftAssertions softAssertions = new SoftAssertions();5 public Statement apply(Statement base, Description description) {6 return new Statement() {7 public void evaluate() throws Throwable {8 setTestInstanceSoftAssertionsField(description, softAssertions);9 base.evaluate();10 softAssertions.assertAll();11 }12 };13 }14}15public class SoftAssertionsExtensionJUnit4Test {16 public SoftAssertionsExtensionJUnit4 softly = new SoftAssertionsExtensionJUnit4();17 public void test() {18 softly.assertThat(1).isEqualTo(2);19 }20}

Full Screen

Full Screen

setTestInstanceSoftAssertionsField

Using AI Code Generation

copy

Full Screen

1SoftAssertions softAssertions = new SoftAssertions();2softAssertions.assertThat("foo").isEqualTo("bar");3SoftAssertions softAssertions = new SoftAssertions();4softAssertions.assertThat("foo").isEqualTo("bar");5SoftAssertions softAssertions = new SoftAssertions();6softAssertions.assertThat("foo").isEqualTo("bar");7SoftAssertions softAssertions = new SoftAssertions();8softAssertions.assertThat("foo").isEqualTo("bar");9SoftAssertions softAssertions = new SoftAssertions();10softAssertions.assertThat("foo").isEqualTo("bar");11SoftAssertions softAssertions = new SoftAssertions();12softAssertions.assertThat("foo").isEqualTo("bar");13SoftAssertions softAssertions = new SoftAssertions();14softAssertions.assertThat("foo").isEqualTo("bar");15SoftAssertions softAssertions = new SoftAssertions();16softAssertions.assertThat("foo").isEqualTo("bar");

Full Screen

Full Screen

setTestInstanceSoftAssertionsField

Using AI Code Generation

copy

Full Screen

1package org.example;2import org.assertj.core.api.SoftAssertions;3import org.junit.jupiter.api.Test;4import org.junit.jupiter.api.extension.ExtendWith;5@ExtendWith(SoftAssertionsExtension.class)6public class SoftAssertionsExtensionTest {7 public void test(SoftAssertions softly) {8 softly.assertThat(1).isEqualTo(1);9 softly.assertThat(2).isEqualTo(2);10 }11}12package org.example;13import org.assertj.core.api.SoftAssertions;14import org.junit.jupiter.api.Test;15import org.junit.jupiter.api.extension.ExtendWith;16@ExtendWith(SoftAssertionsExtension.class)17public class SoftAssertionsExtensionTest {18 public void test(SoftAssertions softly) {19 usingSoftly(softly, () -> {20 assertThat(1).isEqualTo(1);21 assertThat(2).isEqualTo(2);22 });23 }24}25package org.example;26import org.assertj.core.api.SoftAssertions;27import org.junit.jupiter.api.Test;28import org.junit.jupiter.api.extension.ExtendWith;29@ExtendWith(SoftAssertionsExtension.class)30public class SoftAssertionsExtensionTest {31 public void test(SoftAssertions softly) {32 softly.assertThat(1).isEqualTo(1);33 softly.assertThat(2).isEqualTo(2);34 }35}36package org.example;37import org.assertj.core.api.SoftAssertions;38import org

Full Screen

Full Screen

setTestInstanceSoftAssertionsField

Using AI Code Generation

copy

Full Screen

1The SoftAssertionsExtension class has a method setTestInstanceSoftAssertionsField() that can be used to set the field of the test class to a SoftAssertions instance. The following code is an example of how to use the method:2import org.junit.jupiter.api.extension.ExtensionContext;3import org.junit.jupiter.api.extension.ParameterContext;4import org.junit.jupiter.api.extension.ParameterResolutionException;5import org.junit.jupiter.api.extension.ParameterResolver;6public class SoftAssertionsExtension implements ParameterResolver {7 public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {8 return parameterContext.getParameter().getType() == SoftAssertions.class;9 }10 public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {11 return setTestInstanceSoftAssertionsField(extensionContext);12 }13 public static SoftAssertions setTestInstanceSoftAssertionsField(ExtensionContext context) {14 Object testInstance = context.getRequiredTestInstance();15 SoftAssertions softly = new SoftAssertions();16 Class<?> testClass = testInstance.getClass();17 try {18 Field softlyField = testClass.getDeclaredField("softly");19 softlyField.setAccessible(true);20 softlyField.set(testInstance, softly);21 } catch (IllegalAccessException | NoSuchFieldException e) {22 throw new ParameterResolutionException("Unable to set SoftAssertions field", e);23 }24 return softly;25 }26}27import org.assertj.core.api.SoftAssertions;28import org.junit.jupiter.api.Test;29import org.junit.jupiter.api.extension.ExtendWith;30@ExtendWith(SoftAssertionsExtension.class)31public class TestClass {32 private SoftAssertions softly;33 public void testMethod() {34 softly.assertThat(1).isEqualTo(2);35 softly.assertThat(1).isEqualTo(1);36 }37}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful