From 608be2cdc028006a04a7ecc6e1e3d0633641e694 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Tue, 13 Oct 2020 22:25:59 +0200 Subject: [PATCH] Create mock as lenient In order to avoid UnnecessaryStubbingException --- src/main/java/org/simplify4u/sjf4jmock/LoggerFactory.java | 8 ++++---- .../java/org/simplify4u/sl4jmock/test/ExampleTest.java | 6 +++++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/simplify4u/sjf4jmock/LoggerFactory.java b/src/main/java/org/simplify4u/sjf4jmock/LoggerFactory.java index bf47266..88d0514 100644 --- a/src/main/java/org/simplify4u/sjf4jmock/LoggerFactory.java +++ b/src/main/java/org/simplify4u/sjf4jmock/LoggerFactory.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; import org.mockito.Mockito; import org.slf4j.ILoggerFactory; @@ -40,16 +41,15 @@ public class LoggerFactory implements ILoggerFactory { @Override public Logger getLogger(String name) { synchronized (loggers) { - return loggers.computeIfAbsent(name, this::createNewLoggerMock); + return loggers.computeIfAbsent(name, LoggerFactory::createNewLoggerMock); } } @SuppressWarnings("java:S1312") // Loggers should be "private static final" and should share a naming convention - private Logger createNewLoggerMock(String name) { + private static Logger createNewLoggerMock(String name) { LOGGER.debug("Create mock for logger: {}", name); - - Logger mock = mock(Logger.class); + Logger mock = mock(Logger.class, withSettings().lenient()); when(mock.getName()).thenReturn(name); new DelegateMockToSimpleLogger(name).delegate(mock); diff --git a/src/test/java/org/simplify4u/sl4jmock/test/ExampleTest.java b/src/test/java/org/simplify4u/sl4jmock/test/ExampleTest.java index 1b482c7..e097393 100644 --- a/src/test/java/org/simplify4u/sl4jmock/test/ExampleTest.java +++ b/src/test/java/org/simplify4u/sl4jmock/test/ExampleTest.java @@ -26,9 +26,13 @@ import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.junit.MockitoJUnitRunner; import org.simplify4u.sjf4jmock.LoggerMock; import org.slf4j.Logger; +@RunWith(MockitoJUnitRunner.class) public class ExampleTest { private static final String INFO_TEST_MESSAGE = "info log test message"; @@ -36,12 +40,12 @@ public class ExampleTest { private static final String DEBUG_TEST_MESSAGE = "debug log test message"; private static final String DEBUG_TEST_FORMAT = "Debug: {}"; + @InjectMocks private Example sut; @Before public void setup() { LoggerMock.clearInvocations(); - sut = new Example(); }