doReturn?import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Service { String getData() { return "real"; } } public class ServiceTest { @Test void testDoReturn() { Service mockService = mock(Service.class); doReturn("mocked").when(mockService).getData(); String result = mockService.getData(); assertEquals("mocked", result); System.out.println(result); } }
The doReturn method in Mockito sets the return value of the mocked method getData() to "mocked". So when mockService.getData() is called, it returns "mocked" instead of the real method's "real".
doThrow?import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Service { void perform() {} } public class ServiceTest { @Test void testDoThrow() { Service mockService = mock(Service.class); doThrow(new IllegalStateException("fail")).when(mockService).perform(); assertThrows(IllegalStateException.class, () -> mockService.perform()); } }
The doThrow method configures the mock to throw an IllegalStateException when perform() is called. The test expects this exception, so it passes.
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Service { void execute() {} } public class ServiceTest { @Test void testExceptionMessage() { Service mockService = mock(Service.class); doThrow(new RuntimeException("error occurred")).when(mockService).execute(); // Which assertion below is correct? } }
Option B correctly captures the exception thrown by execute() and asserts that its message matches "error occurred". Options B and C use non-existent or incorrect assertion signatures. Option B is invalid because execute() returns void and cannot be compared to a string.
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; class FinalClass { final String finalMethod() { return "real"; } } public class SpyTest { @Test void testDoReturnOnFinal() { FinalClass spy = spy(new FinalClass()); doReturn("mocked").when(spy).finalMethod(); String result = spy.finalMethod(); } }
By default, Mockito cannot mock or stub final methods because of JVM restrictions. Attempting to use doReturn on a final method causes an exception. To mock final methods, additional configuration or tools are needed.
doReturn().when() and when().thenReturn() in Mockito?when().thenReturn() calls the real method when used on spies, which can cause side effects or exceptions. doReturn().when() does not call the real method during stubbing, making it safer for spies.