Mocking member variables of a class using Mockito

前端 未结 9 1794
醉话见心
醉话见心 2020-12-07 10:24

I am a newbie to development and to unit tests in particular . I guess my requirement is pretty simple, but I am keen to know others thoughts on this.

Suppose I h

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 10:29

    Yes, this can be done, as the following test shows (written with the JMockit mocking API, which I develop):

    @Test
    public void testFirst(@Mocked final Second sec) {
        new NonStrictExpectations() {{ sec.doSecond(); result = "Stubbed Second"; }};
    
        First first = new First();
        assertEquals("Stubbed Second", first.doSecond());
    }
    

    With Mockito, however, such a test cannot be written. This is due to the way mocking is implemented in Mockito, where a subclass of the class to be mocked is created; only instances of this "mock" subclass can have mocked behavior, so you need to have the tested code use them instead of any other instance.

提交回复
热议问题