dimanche 28 juin 2015

Using MockitoJUnitRunner.class instead of SpringJUnit4ClassRunner.class

I have a question about the usage of SpringJUnit4ClassRunner.class. For pure Junits or Unit Test cases should we use Spring based annotations such as @Autowired along with SpringJUnit4ClassRunner.class or should we use only the "MockitoJUnitRunner.class" instead with the @RunWith annotation at the top of the Test class?

I mean replacing @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:test-applicationContext.xml" }) with just @RunWith(MockitoJUnitRunner.class at the top of the class. It works for me.

In Junits we normally do not make any external calls such as calls to DB or call to some other web service. We have to mock these external calls using @Mock annotations on this service objects. And then create a real object of the class that we are testing & that depends on these mocks. We can then use @InjectMocks on the real object so that it will be injected with the mocked objects.

Example Service-A->Calls->Service-B->Calls->Service-C

While testing A we should mock Service B & while testing Service-B we should mock Service-C.

Some code Snippet

{
    @RunWith(MockitoJUnitRunner.class)
    public class TestServiceA {
    @Mock
    B mockObj;

    @InjectMocks
    A realObj;

    @Test
    public void testServiceA() {
    .....
    .....
    }

}       

So, I feel for Unit test cases we need not rely on Spring container to provide us the instance of the class we are testing.

Please give your suggestions.

Using SpringJUnit4ClassRunner.class instead of MockitoJUnitRunner.class

Aucun commentaire:

Enregistrer un commentaire