0

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.

Kavan
  • 1
  • 2
  • This does not even compile: 1. `Mockito.spy(new SomeClass.class)`. 2. You call `method2(n1, n2);` while `method2` takes no args 3. @Test on class is not applicable. Please make an effort to post the code that reproduces your problem – Lesiak Jul 15 '20 at 19:56
  • Check out this answer: https://stackoverflow.com/questions/23236338/using-mockito-to-mock-a-local-variable-of-a-method – Shawn Jul 15 '20 at 20:19
  • Hi thanks for the replies, i made the changes, maybe its understandable now? sorry im new to stackoverflow – Kavan Jul 16 '20 at 06:56
  • @alea https://stackoverflow.com/questions/11620103/mockito-trying-to-spy-on-method-is-calling-the-original-method this worked. thanks – Kavan Jul 16 '20 at 07:45

0 Answers0