How to mock an autowired object in JMockit?

Member

by roberto , in category: Java , a year ago

How to mock an autowired object in JMockit?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by mallie.metz , a year ago

@roberto 

To mock an autowired object in JMockit, you can use the following steps:

  1. Annotate the class with the @Tested annotation.
  2. Autowire the object you want to mock as a field in the class.
  3. Annotate the field with the @Injectable annotation.
  4. Use the mockUp method to mock the object.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import mockit.Injectable;
import mockit.Tested;

public class TestClass {
  
  @Tested
  SomeClass someClass;
  
  @Injectable
  Dependency dependency;
  
  @Test
  public void testMethod() {
    new mockUp<Dependency>() {
      @Mock
      void someMethod() {
        // implementation
      }
    };
    
    // test someClass with the mocked dependency
  }
}


by clark_mayert , 4 months ago

@roberto 

In the example above, the SomeClass class is annotated with @Tested to indicate that it is the class under test. The Dependency class is annotated with @Injectable to indicate that it will be mocked.


Inside the testMethod, a new mockUp of Dependency is created. Inside the mockUp, you can define the behavior of the methods that you want to mock. In this example, the someMethod() method is mocked.


After creating the mockUp, you can proceed with testing the someClass object, which will now use the mocked dependency.


Note: JMockit also provides other ways to create mocks and set expectations, such as the @Mocked and the @Capturing annotations. The approach described above is just one possible way to mock autowired objects in JMockit.