How to use StrictJUnitRuleTest class of org.mockitousage.junitrule package

Best Mockito code snippet using org.mockitousage.junitrule.StrictJUnitRuleTest

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*
2 * Copyright (c) 2017 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockitousage.junitrule;
6
7import org.assertj.core.api.Assertions;
8import org.junit.Rule;
9import org.junit.Test;
10import org.mockito.Mock;
11import org.mockito.quality.Strictness;
12import org.mockito.exceptions.misusing.PotentialStubbingProblem;
13import org.mockito.exceptions.misusing.UnfinishedVerificationException;
14import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
15import org.mockito.junit.MockitoJUnit;
16import org.mockitousage.IMethods;
17import org.mockitoutil.SafeJUnitRule;
18
19import static org.junit.Assert.assertEquals;
20import static org.mockito.BDDMockito.given;
21import static org.mockito.BDDMockito.willReturn;
22import static org.mockito.Mockito.*;
23import static org.mockitoutil.TestBase.filterLineNo;
24
25public class StrictJUnitRuleTest {
26
27    @Rule public SafeJUnitRule rule = new SafeJUnitRule(MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS));
28
29    @Mock IMethods mock;
30    @Mock IMethods mock2;
31
32    @Test public void ok_when_no_stubbings() throws Throwable {
33        mock.simpleMethod();
34        verify(mock).simpleMethod();
35    }
36
37    @Test public void ok_when_all_stubbings_used() throws Throwable {
38        given(mock.simpleMethod(10)).willReturn("foo");
39        mock.simpleMethod(10);
40    }
41
42    @Test public void ok_when_used_and_mismatched_argument() throws Throwable {
43        given(mock.simpleMethod(10)).willReturn("foo");
44        mock.simpleMethod(10);
45        mock.simpleMethod(15);
46    }
47
48    @Test public void fails_when_unused_stubbings() throws Throwable {
49        //expect
50        rule.expectFailure(UnnecessaryStubbingException.class);
51
52        //when
53        given(mock.simpleMethod(10)).willReturn("foo");
54        mock2.simpleMethod(10);
55    }
56
57    @Test public void test_failure_trumps_unused_stubbings() throws Throwable {
58        //expect
59        rule.expectFailure(AssertionError.class, "x");
60
61        //when
62        given(mock.simpleMethod(10)).willReturn("foo");
63        mock.otherMethod();
64
65        throw new AssertionError("x");
66    }
67
68    @Test public void why_do_return_syntax_is_useful() throws Throwable {
69        //Trade-off of Mockito strictness documented in test
70
71        //expect
72        rule.expectFailure(PotentialStubbingProblem.class);
73
74        //when
75        when(mock.simpleMethod(10)).thenReturn("10");
76        when(mock.simpleMethod(20)).thenReturn("20");
77    }
78
79    @Test public void fails_fast_when_stubbing_invoked_with_different_argument() throws Throwable {
80        //expect
81        rule.expectFailure(new SafeJUnitRule.FailureAssert() {
82            public void doAssert(Throwable t) {
83                Assertions.assertThat(t).isInstanceOf(PotentialStubbingProblem.class);
84                assertEquals(filterLineNo("\n" +
85                                "Strict stubbing argument mismatch. Please check:\n" +
86                                " - this invocation of 'simpleMethod' method:\n" +
87                                "    mock.simpleMethod(15);\n" +
88                                "    -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.java:0)\n" +
89                                " - has following stubbing(s) with different arguments:\n" +
90                                "    1. mock.simpleMethod(20);\n" +
91                                "      -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.java:0)\n" +
92                                "    2. mock.simpleMethod(30);\n" +
93                                "      -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.java:0)\n" +
94                                "Typically, stubbing argument mismatch indicates user mistake when writing tests.\n" +
95                                "Mockito fails early so that you can debug potential problem easily.\n" +
96                                "However, there are legit scenarios when this exception generates false negative signal:\n" +
97                                "  - stubbing the same method multiple times using 'given().will()' or 'when().then()' API\n" +
98                                "    Please use 'will().given()' or 'doReturn().when()' API for stubbing.\n" +
99                                "  - stubbed method is intentionally invoked with different arguments by code under test\n" +
100                                "    Please use 'default' or 'silent' JUnit Rule.\n" +
101                                "For more information see javadoc for PotentialStubbingProblem class."),
102                        filterLineNo(t.getMessage()));
103            }
104        });
105
106        //when stubbings in the test code:
107        willReturn("10").given(mock).simpleMethod(10) ;  //used
108        willReturn("20").given(mock).simpleMethod(20) ;  //unused
109        willReturn("30").given(mock).simpleMethod(30) ;  //unused
110
111        //then
112        mock.otherMethod(); //ok, different method
113        mock.simpleMethod(10); //ok, stubbed with this argument
114
115        //invocation in the code under test uses different argument and should fail immediately
116        //this helps with debugging and is essential for Mockito strictness
117        mock.simpleMethod(15);
118    }
119
120    @Test public void verify_no_more_interactions_ignores_stubs() throws Throwable {
121        //when stubbing in test:
122        given(mock.simpleMethod(10)).willReturn("foo");
123
124        //and code under test does:
125        mock.simpleMethod(10); //implicitly verifies the stubbing
126        mock.otherMethod();
127
128        //and in test we:
129        verify(mock).otherMethod();
130        verifyNoMoreInteractions(mock);
131    }
132
133    @Test public void unused_stubs_with_multiple_mocks() throws Throwable {
134        //expect
135        rule.expectFailure(new SafeJUnitRule.FailureAssert() {
136            public void doAssert(Throwable t) {
137                assertEquals(filterLineNo("\n" +
138                        "Unnecessary stubbings detected.\n" +
139                        "Clean & maintainable test code requires zero unnecessary code.\n" +
140                        "Following stubbings are unnecessary (click to navigate to relevant line of code):\n" +
141                        "  1. -> at org.mockitousage.junitrule.StrictJUnitRuleTest.unused_stubs_with_multiple_mocks(StrictJUnitRuleTest.java:0)\n" +
142                        "  2. -> at org.mockitousage.junitrule.StrictJUnitRuleTest.unused_stubs_with_multiple_mocks(StrictJUnitRuleTest.java:0)\n" +
143                        "Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class."), filterLineNo(t.getMessage()));
144            }
145        });
146
147        //when test has
148        given(mock.simpleMethod(10)).willReturn("foo");
149        given(mock2.simpleMethod(20)).willReturn("foo");
150
151        given(mock.otherMethod()).willReturn("foo"); //used and should not be reported
152
153        //and code has
154        mock.otherMethod();
155        mock2.booleanObjectReturningMethod();
156    }
157
158    @Test public void rule_validates_mockito_usage() throws Throwable {
159        //expect
160        rule.expectFailure(UnfinishedVerificationException.class);
161
162        //when test contains unfinished verification
163        verify(mock);
164    }
165}
166
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on StrictJUnitRuleTest

    No relevant questions found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)