Mocking a singleton with mockito

后端 未结 7 1092
别跟我提以往
别跟我提以往 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:04

    As a beginner in Software Development, IMO, dependency injection of a singleton class in a driver/otherservice is a good option. As we can control creation of a single instance of the class and still be able to mock the static methods (as you might have guessed, I have util services in my mind) without using something like PowerMock to mock the static methods (IME which was little painful) I am very much open to listen about it from experienced folks from SOLID or Good OO design principle perspective.

    public class DriverSnapshotHandler {
        private FormatterService formatter;
        public DriverSnapshotHandler() {
            this(FormatterService.getInstance());
        }
        public DriverSnapshotHandler (FormatterService formatterService){
               this.formatter = formatterService;
        }
        public String getImageURL() {
            return FormatterService.getInstance().formatTachoIcon();
        }
    }
    
    and then test using Mockito, something like this.
    
    @Test
    public void testGetUrl(){
      FormatterService formatter = mock(FormatterService.class);
      when(formatter.formatTachoIcon()).thenReturn("TestURL");
      DriverSnapshotHandler handler = new DriverSnapshotHandler(formatter);
      assertEquals(handler.getImageURL(), "TestUrl";
    }
    

提交回复
热议问题