All Downloads are FREE. Search and download functionalities are using the official Maven repository.

info.solidsoft.mockito.java8.AssertionMatcher Maven / Gradle / Ivy

Go to download

Mockito add-ons leveraging Java 8 and lambda expressions to make mocking even more compact

There is a newer version: 2.5.0
Show newest version
/*
 * Copyright (C) 2015 Marcin Zajączkowski.
 *
 * Licensed under the Apache License, Version 2.0.
 */
package info.solidsoft.mockito.java8;

import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;

import java.util.function.Consumer;

/**
 * Allows creating inlined ArgumentCaptor with a lambda expression.
 * 

* With Java 8 and lambda expressions ArgumentCaptor can be inlined: * *


 * {@literal @}Test
 * public void shouldAllowToUseAssertionInLambda() {
 *   //when
 *   ts.findNumberOfShipsInRangeByCriteria(searchCriteria);
 *   //then
 *   verify(ts).findNumberOfShipsInRangeByCriteria(assertArg(sc -> assertThat(sc.getMinimumRange()).isLessThan(2000)));
 * }
 * 
* * in comparison to 3 lines in the classic way: * *

 * {@literal @}Test
 * public void shouldAllowToUseArgumentCaptorInClassicWay() {  //old way
 *     //when
 *     ts.findNumberOfShipsInRangeByCriteria(searchCriteria);
 *     //then
 *     ArgumentCaptor captor = ArgumentCaptor.forClass(ShipSearchCriteria.class);
 *     verify(ts).findNumberOfShipsInRangeByCriteria(captor.capture());
 *     assertThat(captor.getValue().getMinimumRange()).isLessThan(2000);
 * }
 *
 * AssertJ assertions (assertThat()) used in lambda generate meaningful error messages in face of failure, but any other assertion can be
 * used if needed/preffered.
 *
 * @param  type of argument
 *
 * @author Marcin Zajączkowski
 */
public class AssertionMatcher implements ArgumentMatcher {

    private static final LambdaAwareHandyReturnValues handyReturnValues = new LambdaAwareHandyReturnValues();

    private final Consumer consumer;
    private String errorMessage;

    private AssertionMatcher(Consumer consumer) {
        this.consumer = consumer;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean matches(T argument) {
        try {
            consumer.accept(argument);
            return true;
        } catch (AssertionError e) {
            errorMessage = e.getMessage();
            return false;
        }
    }

    @Override
    public String toString() {
        return "AssertionMatcher reported: " + errorMessage;
    }

    public static  T assertArg(Consumer consumer) {
        Mockito.argThat(new AssertionMatcher<>(consumer));
        return handyReturnValues.returnForConsumerLambda(consumer);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy