lundi 17 avril 2017

When should we use @InjectMocks?

I have read through a lot of discussion about @Mock & @InjectMocks and still could not find what are the suitable or necessary cases to use @InjectMocks. In fact, I am not sure about what would happen when we use @InjectMocks.

I am testing a import file function, which need a file path (mocked). Consider the following example,

@RunWith(MockitoJUnitRunner.class)
public class myServiceTest {

   @Mock
   myResource res;

   @InjectMocks
   myService service;
   // below also works. Why do we need @inject mock?
   //myService serevice = new myService();

   @Test
   public void testMyFunction {
       when(res.getFilePaht()).thenReturn("/mypath/importfile.txt");
       service.extractData(res);
       assertEquals("myDataInsideFile", service.getData());
   }
}

The above example works ok. If we replace with

myService service = new myService();

it also works. Then what's the point of using @InjectMocks? What's the good thing of it? Please teach me. Thank you.

Aucun commentaire:

Enregistrer un commentaire