Akshat Sood
Akshat Sood

Reputation: 375

InvocationTargetException in Mockito

I'm getting InvocationTarget Exception in my test case. This is the class which I'm trying to test :

public class UpdateHandler implements Handler {
 public void process(UE m, UEC u) {
  try {
   Info info = facade1.queryInfo(string).getInfo();
   Index index = facade2.findindex(string2);
   if(facade3.isWhitelisted() {
    facade2.update(info, index);
   }
  } catch(UpdateException e) {
    //log
  }
}

This is my test file

public class TestFile {
 @Mock
 protected Facade1 facade1;

 @Mock
 protected Facade2 facade2;

 @Mock
 protected Facade3 facade3;

 private Info info;
 private Index index;

 @InjectMocks 
 private UpdateHandler updatehandler;

 @BeforeMethod
 public void beforeTest() {
        MockitoAnnotations.initMocks(this);
    }

 @Test
 public void Test1() {
  info = getInfo();
  index = getIndex();
  updateHandler.process(UEprepare(), null);
  Mockito.when(facade1.queryInfo(Mockito.anyString()).getInfo()).thenReturn(getInfo());
  Mockito.when(facade2.findindex(Mockito.anyString()).thenReturn(getIndex());
  Mockito.when(facade3.isWhitelisted()).thenReturn(true);
  Mockito.verify(facade1, Mockito.times(1).update(info, index);
 }
}

getInfo() and getIndex() are two methods I created in the test file just to create a sample object of Info and Index. UEprepare is a method to prepare a sample object of UE. UM can be null. I've checked that's not the issue.

The error I'm getting is Null pointer exception. Specifically, the value of facade1.queryInfo(string) is null. It's supposed to be an object of type InfoResult from which I can extract an object of Info. I checked the queryInfo method and that does not throw a NPE anywhere. It only throws exception of type UpdateException which I've already handled in my code in try catch.

When I dug deeper, I found an InvocationTargetException. I can't specifically understand where that exception is coming from but I think it's got something to do with the queryInfo method.

I've initialized mocks for all the facades I'm using and I think I've used InjectMocks correctly as well so I'm stuck on how to debug this.

Upvotes: 0

Views: 1398

Answers (1)

Lesiak
Lesiak

Reputation: 26094

There are 2 errors in your code:

Order of methods

You have:

  • call of method under test
  • setting expectations Mockito.when
  • verification of expectations Mockito.verify

while it should be

  • setting expectations Mockito.when
  • call of method under test
  • verification of expectations Mockito.verify

Chained expectations

Mockito.when(facade1.queryInfo(Mockito.anyString()).getInfo()).thenReturn(getInfo());

You need additional mock for result of queryInfo call, let's say @Mock QueryInfo queryInfo. Then, you need 2 calls for setting this expectation:

Mockito.when(facade1.queryInfo(Mockito.anyString()).thenReturn(queryInfo);
Mockito.when(queryInfo.getInfo()).thenReturn(getInfo());

Upvotes: 1

Related Questions