dhamini-poornachandra / mockito

Automatically exported from code.google.com/p/mockito
0 stars 0 forks source link

Erroneous InvalidUseOfMatchersException when mock set up before spy set up #431

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
When a spy is set up after a mock has been set up an 
InvalidUserOfMatchersException is raised.
This short test case demonstrates this bug.

    public static class DemoBug {

        public static class Calculator {

            public int calculate() {
                return 2;
            }
        }

        @Mock
        private Calculator calculatorMock;

        public static class MyEmployee {
            public String getName() {
                return "adam";
            }
        }

        @Mock
        private MyEmployee myEmployee;

        public static class DoCalcs {

            private Calculator calculator;

            public DoCalcs(Calculator c, MyEmployee e) {
                calculator = c;
            }

            public int doCalculation() {
                return calculator.calculate();
            }
        }

        @Test
        public void spyBug() {
            MyEmployee realEmployee = new MyEmployee();
            MyEmployee spyEmployee = Mockito.spy(realEmployee);

            DoCalcs doCalcs = new DoCalcs(calculatorMock, spyEmployee);

            //This line produces an error, comment it out and test will pass.
            given(calculatorMock.calculate()).willReturn(anyInt());

            //Or move this line up before the previus one..
            Mockito.when(spyEmployee.getName()).thenReturn("bob");
        }

    }

Original issue reported on code.google.com by johnmich...@gmail.com on 26 Apr 2013 at 2:48

GoogleCodeExporter commented 8 years ago
Hi,

Well, no the framework is correct about InvalidUseOfMatchersException.
`org.mockito.Matchers.anyInt()`, which is an argument matcher is misplaced in a 
`thenReturn` call, so Mockito cannot find the argument for which this matcher 
should be used.

You cannot use matchers anywhere else than in calls you want to stub.

Original comment by brice.du...@gmail.com on 29 Apr 2013 at 11:02