Skip to content

Instantly share code, notes, and snippets.

@GopinathMR
Last active April 20, 2021 08:45
Show Gist options
  • Save GopinathMR/b9341fed94573b6056b5 to your computer and use it in GitHub Desktop.
Save GopinathMR/b9341fed94573b6056b5 to your computer and use it in GitHub Desktop.
how to mock methods in Singleton
// sample code written to showcase how to use Mockito to mock certain methods to test logic in Singleton classes
public class MySingletonClass {
// not lazy initiated object.
private static final MySingeltonClass INSTANCE = new MySingletonClass();
// can be used by unit test by Mocking it. Mockito invokes this default constructor.
@VisibleForTesting
MySingletonClass {
}
// method used by main code
public static final MySingletonClass getInstance() {
return INSTANCE;
}
// a method you want to mock
public String getRecentMessage(UUID userId) {
// some wierd logic just to showcase some logic
List<UserMessage> messages = getUserMessagesFromDB(userId, 1);
if (messages == null || messages.size() == 0) {
UserMessage message = new UserMessage(userId, "initial message");
saveMessageToDB(message);
return message;
} else {
return messages.get(0);
}
}
@VisibleForTesting
void saveMessageToDB(UserMessage message) {
UserMessageDao.getInstance().saveMessage(message);
}
@VisibleForTesting
List<UserMessage> getUserMessagesFromDB(UUID userId, int recent) {
// accesssing databse here..
return UserMessageDao.getInstance().getUserMessages(userId, recent)
}
}
// Unit test class in same package as main class
public class MySingletonClassTest {
@Mock
// invokes default constructor. So during unit testing, there are 2 instances created, one for MySingletonClass (due to static initialization)
// and 2nd one for proxy class generated which derives from MySingletonClass.
// If that is a problem, you can change Singleton to be lazy initialization. I have not put lazy initialization code to focus
// on mockito usage for singleton.
private MySingletonClass singletonInstance;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testWhenNoMessageExists() {
when(singletonInstance.getUserMessagesFromDB(any(UUID.class), anyInt()).thenReturn(null);
UUID userId = UUID.randomUUID();
UserMessage message = singletonInstance.getRecentMessage(userId);
assertTrue(message != null);
assertEquals("initial message", message.getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment