Wednesday, December 14, 2022

junit best way to set field that is set on a mocked service

 If you're using JUnit to write unit tests, one way to set a field that is set on a mocked service is to use the @Mock and @InjectMocks annotations.

Here's an example of how you might do this:

@Mock private SomeService someService; @InjectMocks private SomeClass someClass; @Before public void setUp() { MockitoAnnotations.initMocks(this); }

In the example above, @Mock is used to create a mocked instance of SomeService. Then, @InjectMocks is used to inject this mocked service into an instance of SomeClass, which is the class that we want to test. Finally, the setUp() method is used to initialize the mocked objects using MockitoAnnotations.initMocks().

Once you have set up the mock objects using these annotations, you can use Mockito's when() and thenReturn() methods to specify the behavior of the mocked service. For example:

when(someService.someMethod()).thenReturn(someValue);

This tells Mockito to return someValue when someMethod() is called on the someService mock. This allows you to control the behavior of the mocked service, so you can test different scenarios in your unit tests.

No comments:

Post a Comment