Skip to content

Instantly share code, notes, and snippets.

@LiSongMWO
Last active October 29, 2016 10:52
Show Gist options
  • Save LiSongMWO/cff3b7cb60b9f1d903a6ca8ea5b7d0c9 to your computer and use it in GitHub Desktop.
Save LiSongMWO/cff3b7cb60b9f1d903a6ca8ea5b7d0c9 to your computer and use it in GitHub Desktop.
UnnecessaryStubbingException SSCCE
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class SillyTest {
static class ClassUnderTest {
LinearRamp ramp;
public ClassUnderTest(LinearRamp aRamp) {
ramp = aRamp;
}
int calc(int x) {
// Un-commenting this breaks the test even though the behaviour is correct
// if (x == 0) return 0;
return ramp.compute(x);
}
}
static class LinearRamp {
int scale;
LinearRamp(int aScale) {
scale = aScale;
}
int compute(int x) {
return scale * x;
}
}
final LinearRamp ramp = mock(LinearRamp.class);
final ClassUnderTest cut = new ClassUnderTest(ramp);
@Test
public void testCalcOfNonZero() {
when(ramp.compute(3)).thenReturn(6);
assertEquals(6, cut.calc(3));
}
@Test
public void testCalcOfZeroReturnsZero() {
when(ramp.compute(0)).thenReturn(0);
assertEquals(0, cut.calc(0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment