Search code examples
javadependency-injectionmockitojmockit

Mockito vc JMockit and Dependency injetion


I found this article quite interesting http://www.jayway.com/2012/02/25/mockito-and-dependency-injection/ it says that Mockito supports dependency injection by using constructor arguments, setter methods and field injection. I was wondering if JMockit does the same, so far I haven't find no one using JMockit and dependency injection.


Solution

  • JMockit supports dependency injection via arguments and properties. The test class must contain one or more mock properties or mock parameters declared to be @Injectable. The business object you would like to test need to be declared with the annotation @Tested. The @Tested annotation automatically creates an instance of the class and injecting the mocked dependencies.

    public class SomeTest {
       @Tested CodeUnderTest tested;
       @Injectable Dependency dep1;
       @Injectable AnotherDependency dep2;
       @Injectable int someIntegralProperty = 123;
    
       @Test
       public void someTestMethod(@Injectable("true") boolean flag, @Injectable("Mary") String name)
       {
          // Record expectations on mocked types, if needed.
    
          tested.exerciseCodeUnderTest();
    
          // Verify expectations on mocked types, if required.
       }
    }
    

    You can find more detailed information here: http://jmockit.github.io/tutorial/BehaviorBasedTesting.html#tested (official docs)