BAEL-2125 - Mockito UnnecessaryStubbingException

This commit is contained in:
Jon Cook 2019-05-02 14:47:14 +02:00
parent 0e446c9df0
commit 3297adc992
2 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,51 @@
package com.baeldung.mockito.misusing;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
public class ExpectedTestFailureRule implements MethodRule {
private final MethodRule testedRule;
private FailureAssert failureAssert = null;
public ExpectedTestFailureRule(MethodRule testedRule) {
this.testedRule = testedRule;
}
@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
return new Statement() {
public void evaluate() throws Throwable {
try {
testedRule.apply(base, method, target)
.evaluate();
} catch (Throwable t) {
if (failureAssert == null) {
throw t;
}
failureAssert.doAssert(t);
return;
}
}
};
}
@SuppressWarnings("unchecked")
public void expectedFailure(final Class<? extends Throwable> expected) {
FailureAssert assertion = t -> Assert.assertThat(t, Matchers.isA((Class<Throwable>) expected));
this.expectedFailure(assertion);
}
private void expectedFailure(FailureAssert failureAssert) {
this.failureAssert = failureAssert;
}
@FunctionalInterface
private interface FailureAssert {
abstract void doAssert(Throwable t);
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.mockito.misusing;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.junit.MockitoJUnit;
import org.mockito.quality.Strictness;
public class MockitoUnecessaryStubUnitTest {
@Rule
public ExpectedTestFailureRule rule = new ExpectedTestFailureRule(MockitoJUnit.rule()
.strictness(Strictness.STRICT_STUBS));
@Mock
private ArrayList<String> mockList;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void givenUnusedStub_whenInvokingGetThenThrowUnnecessaryStubbingException() {
rule.expectedFailure(UnnecessaryStubbingException.class);
when(mockList.add("one")).thenReturn(true);
when(mockList.get(anyInt())).thenReturn("hello");
assertEquals("List should contain hello", "hello", mockList.get(1));
}
@Test
public void givenLenientdStub_whenInvokingGetThenDontThrowUnnecessaryStubbingException() {
lenient().when(mockList.add("one"))
.thenReturn(true);
when(mockList.get(anyInt())).thenReturn("hello");
assertEquals("List should contain hello", "hello", mockList.get(1));
}
}