Search code examples
javajava-8functional-interface

Java 8 Function - "wrapper" function that does something before executing given lambda?


We have the following scenario:

Mid-test, some context variables need to be updated. Where exactly in the test and what exactly should happen is variable. I would like to provide a "wrapper" function, which sets up some context variables and then performs all assertions that were given to it in the function call.

So, something like the following:

public void withDefaultContextA(Function<???, Void> noArgsCall) {

    setupDefaultContextA();
    noArgsCall.invoke() // not sure how apply() would be invoked here
}

or:

public void withContextA(BiFunction<???, Context, Void> providedContextCall) {

    setupContext(providedContext); // not sure how apply() would be invoked here
}

And in the corresponding test, these should be invoked as follows:

@Test
public void testSomething() {

    withDefaultContextA(() -> {
        ... // do some asserts
    }

    withContext((new Context(...)) -> {
        ... // do some asserts
    }
}

How can I achieve this? Can Java 8 Functions be used in this manner? If not, is there another way I can achieve this?


Solution

  • It seems you want to decorate any given Runnable (you use Function and BiFunction in your question, but as they return Void and seem to receive no arguments, using Runnable seems more appropriate here).

    You can do it this way:

    public static void withDefaultContext(Runnable original) {
        setupDefaultContextA();
        original.run();
    }
    

    Then, you could use the above method as follows:

    withDefaultContext(() -> {
        // do some asserts
    });
    

    Or with a specific context:

    public static void withContext(Context context, Runnable original) {
        setupContext(context);
        original.run();
    }
    

    Usage:

    withContext(new Context(...), () -> {
        // do some asserts
    });