2

I want to use a mock DAO to unit test the service layer in my spring application. In the DAO, it's seesinoFactory is injected using @Inject.

When the test class is configured with @RunWith(MockitoJUnitRunner.class)

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
    @Mock
    private MyDao myDaoMock;

    @InjectMocks
    private MyServiceImpl myService;
}

The output is just as expected.

When I changed the configuration to using @RunWith(SpringJUnit4ClassRunner.class)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/ServiceTest-context.xml")
public class ServiceTest {
    @Mock
    private MyDao myDaoMock;

    @InjectMocks
    private MyServiceImpl myService;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
    }
}

The exception,"No qualifying bean of type [org.hibernate.SessionFactory] found for dependency", will be thrown if sessionFactory bean is not available in ServiceTest-context.xml.

What I don't understand is MyDao is annotated with @Mock already, why is sessionFactory still needed?

2
  • 1
    Remember that the initialisation performed by the Spring runner happens BEFORE the call to initMocks. So the Spring runner won't see that the MyDao is actually a mock - it hasn't been instantiated yet; and Spring doesn't understand the @Mock annotation, so it doesn't know that there WILL be a mock here. Does that make sense? Commented Aug 6, 2013 at 20:10
  • @David, thank you for the response. After I removed the the annotations @RunWith and @ContextConfiguration, it then worked as expected. Commented Aug 6, 2013 at 23:25

1 Answer 1

2

you must use @RunWith(MockitoJUnitRunner.class) to initialize these mocks and inject them.

  1. @Mock creates a mock.
  2. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock or @Spy annotations into this instance.

Or Using Mockito.initMocks(this) as follows:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {

    @Autowired
    @InjectMocks
    TestTarget sut;

    @Mock
    Foo mockFoo;

    @Before
    /* Initialized mocks */
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void someTest() {
         // ....
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The question is a while ago already, but your answer would be helpful to others, thx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.