Mocking a singleton with mockito

后端 未结 7 1052
别跟我提以往
别跟我提以往 2020-12-08 00:50

I need to test some legacy code, which uses a singleton in a a method call. The purpose of the test is to ensure that the clas sunder test makes a call to singletons method.

相关标签:
7条回答
  • 2020-12-08 01:19

    I think it is possible. See an example how to test a singleton

    Before a test:

    @Before
    public void setUp() {
        formatter = mock(FormatterService.class);
        setMock(formatter);
        when(formatter.formatTachoIcon()).thenReturn(MOCKED_URL);
    }
    
    private void setMock(FormatterService mock) {
        try {
            Field instance = FormatterService.class.getDeclaredField("instance");
            instance.setAccessible(true);
            instance.set(instance, mock);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    

    After the test - it is important to clean up the class, because other tests will be confused with the mocked instance.

    @After
    public void resetSingleton() throws Exception {
       Field instance = FormatterService.class.getDeclaredField("instance");
       instance.setAccessible(true);
       instance.set(null, null);
    }
    

    The test:

    @Test
    public void testFormatterServiceIsCalled() {
        DriverSnapshotHandler handler = new DriverSnapshotHandler();
        String url = handler.getImageURL();
    
        verify(formatter, atLeastOnce()).formatTachoIcon();
        assertEquals(MOCKED_URL, url);
    }
    
    0 讨论(0)
提交回复
热议问题