1

I want to test a service class.

class Service {

public List<A> mainMethodToTest() {
   //calling another method to get some values
   List<A> list = getImportantValues();
   process list;
   return list; 
}

public getimportantValues() {
   return new List<A>();
}
}

I want to test this service class method 'mainMethodToTest()' using Mockito and mock the call to getimportantValues() method.

Here is the test class I wrote.

class TestService {

private Service service;

@Before
public void setup() {
    service = Mockito.spy(new Service);
}

@Test
public void testMainMethodToTest() {
    Mockito.doReturn(new List<A>()).when(service).getimportantValues();

    Assert.assertNotNull(service.mainMethodToTest());  /// this call throws NullPointerException because somehow it is not treating the service as a real instance of the Service object but a mock.
}
}

The last call in Assert to method 'mainMethodToTest()' throws NullPointer because it takes the service as null and not an instance.

Can someone please help me to understand what am I doing wrong in here.

TIA

Manni
  • 27
  • 1
  • 7
  • How are you running the test, it seems that the setup method annotated with @Before is not executed before your test – Radu Sebastian LAZIN Sep 10 '21 at 03:50
  • Hi Radu, It is going in the setup method. I have verified it with a breakpoint in debug mode. – Manni Sep 10 '21 at 04:27
  • 1
    If the setup method is executed before your test then the service object should be initialized: service = Mockito.spy(new Service()); (thus not null). In your example there are many syntax errors as well just as a note. – Radu Sebastian LAZIN Sep 10 '21 at 05:09
  • Please provide the whole implementation not just the pseudo code. It might be an issue related with the step 'process list'. – Marcin Rzepecki Sep 10 '21 at 06:02
  • @RaduSebastianLAZIN I know about the sytax errors. Just typed it on the fly. Please ignore those. – Manni Sep 10 '21 at 13:50

0 Answers0