I\'m trying to replace an @Autowired
object with a Mockito mock object. The usual way of doing this was with xml using Springockito:
Moving away from the now unmaintained (as of this writing) Spingockito-annotations and to Mockito, we have a way of doing this very simply:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration
public class MyTestClass {
@Mock MockInterface mockObj;
// test code
}
If you're using a real object, but would like to mock a dependency within it, for instance testing a service layer with DAO:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration
public class MyTestClass {
@InjectMocks RealService;
@Mock MockDAO mockDAO;
// test code
}
Finally, this can also be applied to Spring-boot, but using annotation initialization within setUp()
until multiple class runners are supported:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyMainSpringBootClass.class)
public class MyTestClass {
@InjectMocks RealService;
@Mock MockDAO mockDAO;
@Before
public final void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
}
// test code
}