Bala Murugan
Bala Murugan

Reputation: 11

How to Mock the Lambda expression using Mockito

How to Mock the Lambda expression using Mockito

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

lambda

items.forEach(item->System.out.println(item));

items.forEach(item->{if("C".equals(item)){System.out.println(item);}});

Upvotes: 1

Views: 3037

Answers (1)

amseager
amseager

Reputation: 6391

Aside from discussing the purpose of doing this - practically you need to extract consumers from forEach() to separate methods (with the default modifier at least), and in your test class you should use Mockito.spy() functionality to mock them.

(If you haven't yet familiar with the spying principle - it's like a partial mocking of the testing object. The good article about it: https://www.baeldung.com/mockito-spy).

How it actually can be:

  1. Your main class (let it be called "TestApp"):
public class TestApp {

    public void someRealMethod() {
        List<String> items = new ArrayList<>();
        items.add("A");
        items.add("B");
        items.add("C");
        items.add("D");
        items.add("E");

        items.forEach(lambdaForMocking());
        items.forEach(anotherLambdaForMocking());
    }

    Consumer<String> lambdaForMocking() {
        return item -> System.out.println(item);
    }

    Consumer<String> anotherLambdaForMocking() {
        return item -> {
            if ("C".equals(item)) {
                System.out.println(item);
            }
        };
    }
}
  1. Your test class:
public class TestAppTest {

    @Test
    public void lambdaMockingTest() {
        TestApp testApp = new TestApp();
        TestApp spy = Mockito.spy(testApp);

        Mockito.when(spy.lambdaForMocking()).thenReturn(item -> {});
        Mockito.when(spy.anotherLambdaForMocking()).thenReturn(item -> {});

        spy.someRealMethod();

        //Asserts...
    }
}

In "thenReturn" parts you can define any consumers that you want (I left them empty, for example).

Upvotes: 1

Related Questions