6

I am trying to pass a mock object to test method through 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 both times a null object is passed. What is the reason behind 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 in the same method using data provider. Is there a way for it?

Caesar
  • 1,092
  • 12
  • 19

2 Answers2

3

Testng is calling methods in this specific order: serviceData, beforeMethod and m1.

If you want to pass a mock with a data provider, you have to create it before or into the data provider method.

juherr
  • 5,640
  • 1
  • 21
  • 63
3

You also can use @BeforeTest method, that is run before @DataProvider method. Since @BeforeTest is performed before, the @DataProvider method is able to use the mocks.

@BeforeTest is not to be confused with @BeforeMethod. See What is the difference between BeforeTest and BeforeMethod in TestNG.

boltup_im_coding
  • 6,345
  • 6
  • 40
  • 52
androberz
  • 744
  • 10
  • 25
  • 1
    @boltup_im_coding could you clarify what is incorrect? It works for me at least for the testng-6.9.12.jar. If I initializing mock in the '@BeforeTest', I'm able to return it via '@DataProvider'. – androberz Aug 16 '18 at 14:55
  • @boltup_im_coding what about removing the vote down? :) Thanks. – androberz Aug 18 '18 at 15:05