How can I pass a mock object to a data provider using Mockito TestNG?

I am trying to pass a mock object to a test method through a data provider. Below is my test class:

@Test public class FirstTest { @InjectMocks First firstSpy; @Mock Second secondMock; @Mock Third thirdMock; @BeforeMethod public void beforeMethod() { firstSpy = Mockito.spy(new First()); MockitoAnnotations.initMocks(this); } @DataProvider private final Object[][] serviceData() { return new Object [][] { {thirdMock, 1}, {null, 2} }; } @Test(dataProvider="serviceData") public void m1(Third thirdObject, int noOfTimesm3Called) { Mockito.doReturn(secondMock).when(firstSpy).m4(); Mockito.doReturn(thirdObject).when(secondMock).m2(); firstSpy.m1(); verify(firstSpy, times(noOfTimesm3Called)).m3(); } } 

However, when I run this, it displays

 PASSED: m1(null, 2) FAILED: m1(null, 1) 

which means that both times an empty object is passed. What is the reason for this? And how can I get the desired behavior? I want to avoid any if-else statements in the test method and want to test both cases with the same method using the data provider. Is there any way to do this?

+5
source share
2 answers

Testng calls methods in this particular order: serviceData, beforeMethod and m1.

If you want to pass the layout to the data provider, you need to create it before or in the data provider method.

+1
source

You can also use the @BeforeTest method, which runs before @DataProvider .

0
source

Source: https://habr.com/ru/post/1232983/


All Articles