Reputation: 51
I have the following service class :
@Component
public class ABC {
@Autowired private SomeClass assumeRoles;
@Override
public @NotNull Optional<Something> translate(int id) {
// Some Code
SomeClass result = assumeRoles.getRole(id);
}
}
Now I want to write Junit for my class, I don't want Role.getRole(id)
to be get called, instead of that I want to mock this function call, with some dummy value.
So can I do that?
I have my Junit class as
@RunWith(MockitoJUnitRunner.class)
public class ABCTest {
@InjectMocks
private ABC test = new ABC();
@Mock
private SomeClass assumeRoles;
@Test
public void testTranslate() {
ABC result = test.translate(id);
}
}
Upvotes: 1
Views: 87
Reputation: 3197
BTW, field injection
is not recommended by the spring team explained at here: https://blog.marcnuri.com/field-injection-is-not-recommended/
So, you'd better mark the field final
if required: private final SomeClass assumeRoles;
, then provide a constructor like this:
public ABC(SomeClass assumeRoles) {
this.assumeRoles = assumeRoles;
}
In this way, it would be easier to pass the dummy SomeClass
to the constructor to get an instance of ABC
.
Upvotes: 0
Reputation: 4088
You have already marked SomeClass assumeRoles
as @Mock
, you can mock the Role.getRole(id);
statement as follows.
Mockito.when(assumeRoles.getRole(Mockito.any(id))).thenReturn(someResult);
I have answered the question after making some assumptions, I suggest you to improve the code snippet you have provided with correct variable and class names.
Upvotes: 1