From 75afba12d1dcc269cdbeb97060ef6f8a40082b1f Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Mon, 4 Dec 2023 13:18:04 +0000 Subject: [PATCH] BAEL-7240 Add example code for verifying lambda calls with mockito --- .../baeldung/lambdacalls/LambdaExample.java | 26 ++++++++++++ .../lambdacalls/LambdaCallsUnitTest.java | 41 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java b/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java new file mode 100644 index 0000000000..bc6274eb18 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java @@ -0,0 +1,26 @@ +package com.baeldung.lambdacalls; + +import java.util.ArrayList; + +public class LambdaExample { + + private BrickLayer brickLayer = new BrickLayer(); + + static ArrayList bricksList = new ArrayList<>(); + + public void createWall(String bricks){ + Runnable build = () -> brickLayer.layBricks(bricks); + build.run(); + } + + public ArrayList getBricksList(){ + return bricksList; + } + + static class BrickLayer { + void layBricks(String bricks){ + bricksList.add(bricks); + } + } + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java new file mode 100644 index 0000000000..67127c641c --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.lambdacalls; + +import static com.baeldung.lambdacalls.LambdaExample.*; +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class LambdaCallsUnitTest { + + @Mock + private/**/ BrickLayer brickLayer; + @InjectMocks + private LambdaExample lambdaExample; + + @Test + public void whenCallingALambda_thenTheInvocationCanBeConfirmedWithCorrectArguments(){ + String bricks = "red bricks"; + lambdaExample.createWall(bricks); + verify(brickLayer).layBricks(bricks); + } + + @Test + public void whenCallingALambda_thenCorrectBehaviourIsPerformed(){ + LambdaExample lambdaExample = new LambdaExample(); + String bricks = "red bricks"; + + lambdaExample.createWall(bricks); + ArrayList bricksList = lambdaExample.getBricksList(); + + assertEquals(bricks, bricksList.get(0)); + } + +}