For example I have handler:
@Component
public class MyHandler {
@AutoWired
private MyDependency myDependency;
@Value("${some.count}")
private int someCount;
public int someMethod(){
if (someCount > 2) {
...
}
}
to test it I wrote the following test:
@RunWith(MockitoJUnitRunner.class}
class MyHandlerTest {
@InjectMocks
MyHandler myHandler;
@Mock
MyDependency myDependency;
@Test
public void testSomeMethod(){
ReflectionTestUtils.setField(myHandler, "someCount", 4);
myHandler.someMethod();
}
}
I can mock variable someCount using ReflectionTestUtils
. Can I somehow mock it using Mockito annotation?
@InjectMocks is the Mockito Annotation. It allows you to mark a field on which an injection is to be performed. Injection allows you to, Enable shorthand mock and spy injections.
Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.
@MockBean with @QualifierIf an interface has more than one implementation class then to choose the exact class for dependency injection, @Qualifier annotation is used. Here we will show the demo to use @MockBean with @Qualifier annotation. Find the classes used in our unit test class.
@Mock: It is used to mock the objects that helps in minimizing the repetitive mock objects. It makes the test code and verification error easier to read as parameter names (field names) are used to identify the mocks. The @Mock annotation is available in the org. mockito package.
Just use constructor injection:
@Component
public class MyHandler {
private MyDependency myDependency;
private int someCount;
@Autowired
public MyHandler(MyDependency myDependency,
@Value("${some.count}") int someCount){
this.myDependency = myDependency;
this.someCount = someCount;
}
public int someMethod(){
if (someCount > 2) {
...
}
}
and you don't need to use InjectMocks nor reflection in test. You will just create testing object via constructor and pass in the someCount value. Annotations will be ignored during test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With