Final answer:
To mock a method in JUnit 5, you can use the Mockito framework. First, add the Mockito dependency to your project. Then, create a mock object using the annotation and define the behavior of the mocked method using the when method and the thenReturn method.
Step-by-step explanation:
To mock a method in JUnit 5, you can use the Mockito framework. Mockito is a popular Java testing framework that allows you to create mock objects and stub method behaviors.
- First, you need to add the Mockito dependency to your project's build file.
- Next, you can use the annotation to create a mock object of the class that contains the method you want to mock.
- Finally, you can use the when method to define the behavior of the mocked method and the thenReturn method to specify the return value.
Here's an example:
ExtendWith(MockitoExtension.class)
public class MyClassTest {
private MyClass myClass;
public void testMockedMethod() {
when(myClass.mockedMethod()).thenReturn("Mocked Value");
// Rest of the test code
}
}