Junit and Mocking and spy

Index

  • Junit
  • Mockito
  • testing private method (reflection ,powermock)

2 testing fameworks- MOckito abd Sping testing

MOckMOckBean
annotationpary of MockitoframeworkSPring testing framework
framework@RunWith(MockitoJUnitRunner.class) public class MyServiceTest { @Mock private MyRepository myRepository;@SpringBootTest public class MyServiceIntegrationTest { @Autowired private MyService myService; @MockBean private MyRepository myRepository;
PurposeUnitTetsingIntegration testing

Spy vs Mock

@spy@Mock
Functionalitypartially mocked version of a real object.complete replacement for a real object.
CreationWraps an existing objectCreates a new object
ControlPartial control (can define specific behaviors for specific methods)Full control over behavior
Use caseTesting interactions within a real object with some real behaviorIsolating dependencies, unit testing with specific behavior
accesscan access private methods of the original objectcannot access private methods of the original object
examplebelow codebelow code //

Mock usage

// Interface we want to test
public interface EmailService {
  void sendEmail(String recipient, String message);
}

// Test class using mock
@Test
public void testSendEmail() {
  // Create a mock object of EmailService
  EmailService mockEmailService = Mockito.mock(EmailService.class);

  // Define behavior for the mock object
  Mockito.when(mockEmailService.sendEmail("user@example.com", "Hello world!")).thenReturn(true);

  // Use the mock object in your test logic
  myService.sendNotification(mockEmailService, "user@example.com", "Hello world!");

  // Verify interactions with the mock object
  Mockito.verify(mockEmailService).sendEmail("user@example.com", "Hello world!");
}

IN above example :

  • We create a mock object of EmailService using Mockito.mock.
  • We define behavior for the sendEmail method using Mockito.when. Here, it always returns true.
  • We use the mock object in the test and verify its interaction later.

Spy usage

// Real implementation of EmailService
public class RealEmailService implements EmailService {
  @Override
  public void sendEmail(String recipient, String message) {
    // Send email logic goes here (not shown for simplicity)
  }
}

// Test class using spy
@Test
public void testSendEmailWithSpy() {
  // Create a real object
  EmailService realEmailService = new RealEmailService();

  // Create a spy object from the real object
  EmailService spyEmailService = Mockito.spy(realEmailService);

  // Define behavior for specific method (optional)
  Mockito.when(spyEmailService.sendEmail("admin@example.com", "Alert!")).thenReturn("Sent successfully");

  // Use the spy object in your test logic
  myService.sendNotification(spyEmailService, "user@example.com", "Hello world!");
  myService.sendNotification(spyEmailService, "admin@example.com", "Alert!");

  // Verify interactions (optional)
  Mockito.verify(spyEmailService, times(2)).sendEmail(anyString(), anyString());
}

IN above example :

  • Create a real RealEmailService object.
  • Create a spy of the RealEmailService using Mockito.spy.
  • Define behavior for the sendEmail method to return a specific message for “admin@example.com” email.
  • Use the spy object and verify interactions (optional).

		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
			<version>1.7.4</version>
		</dependency>

https://www.learnbestcoding.com/post/21/unit-test-private-methods-and-classes

REfernce

https://www.tutorialspoint.com/mockito/mockito_spying.htm