I'm new to testing, using mockito and junit for testing. The class along with the test method looks like this. Edit: Made corrections to the method.
class SomeClass
{
Data data;
public Data method1(int n1, int n2)
{
data = method2(n1, n2);
if (data != null && data.something()!=null && !data.something().isEmpty())
{
// other instructions
}
return data;
}
Data method2(int n1, int n2)
{
Data data1 = Some calculations;
return data;
}
}
//Test class
@Mock
Data data;
@Test
public void testData()
{
@Test
public void getReceivingDataTest()
{
SomeClass mock = Mockito.spy(new SomeClass.class);
when(mock.method2(1,1)).thenReturn(data);
mock.method1(1,1);
}
}
Here I'm trying to set the value for the received data from the method2 from the test method, but unfortunately I'm not able to mock the local variable Data data. It calls the real method method2 and gets a null value and throws a null exception. I have tried using mock instead of spy and i get the same error. What do i do? edit: method2() is calling another service which since im mockinf it, always returns null and the "other instructions" inside method1() are not executed.