Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I inject primitive variable into mocked class using annotation?

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?

like image 589
Vova Yatsyk Avatar asked Jun 10 '15 15:06

Vova Yatsyk


People also ask

What does InjectMocks annotation do?

@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.

Which annotation is used for mocking dependency?

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.

Can we use @qualifier with @mock?

@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.

What is @mock annotation in Java?

@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.


1 Answers

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.

like image 136
luboskrnac Avatar answered Nov 15 '22 08:11

luboskrnac