4

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?

filpa
  • 3,651
  • 8
  • 52
  • 91
  • 2
    What about using `Consumer`? a void method which accepts as the only argument a `Context` – Lino Jan 22 '19 at 14:45
  • Agree with Lino, `Function` returns a value. Seems like `Consumer` and `BiConsumer` are a better fit for this use case. – Mike Jan 22 '19 at 14:47

1 Answers1

6

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
});
fps
  • 33,623
  • 8
  • 55
  • 110
  • 1
    Exactly what I needed. I couldn't think of the word *decorator*. Might've led to a more fruitful Google search. :) Thanks! – filpa Jan 22 '19 at 15:51