0

I have below implementation of classes.. 'EmpAddress' is an interface & 'EmployeeInterfaceFactory' is a class which has static method 'getAddressImpl' that provides EmpAddress Implemented class Object... I have JUnit method as below where I am getting Null Pointer Exception... Need help/suggestion in implementing this JUnit...

***************************************************************************
public class Employee(){

private Address address = new Address();

public String getEmployeeDetails(){
  String details = address.getDetails();
  return details;
}
}
***************************************************************************
public Address address(){

private EmpAddress empAddress = EmployeeInterfaceFactory.getAddressImpl();

public String getDetails(){

String details = empAddress.getEmpDetails();  // Null pointer exception coming here
return details;
}
}
****************************************************
@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeInterfaceFactory.class})
public class EmployeeTest(){

Employee emp;
EmpAddress empAddress;

@Before
public void setUp(){
 emp = new Employee();
 empAddress = createMock(EmpAddress.class);
 mockStatic(EmployeeInterfaceFactory.class);
}

@Test
public void getEmployeeDetailsTest(){
  expect(EmployeeInterfaceFactory.getAddressImpl()).andReturn(empAddress);
  expect(empAddress.getEmpDetails()).adnReturn("testing data");

  String result = emp.getEmployeeDetails();
}
}
Balaji211
  • 257
  • 1
  • 5
  • 18
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – 9ilsdx 9rvj 0lo Jun 09 '21 at 06:32
  • nope, no where JUnit implementation is available. I can't change the code.. Is there any way to mock those lines to make JUnit pass ? – Balaji211 Jun 09 '21 at 06:51
  • @Balaji211 please post the stacktrace so that we can debug it properly. – AR1 Nov 11 '21 at 12:09

1 Answers1

0

check if you are getting empAdress at line private EmpAddress empAddress = EmployeeInterfaceFactory.getAddressImpl();, may be you can move it to setUp method, call setUp in getDetails method, so that empAdress is not null when you are trying to access it in getDetails

and in TestCase, you are returning empAddress, which is not yet initialized, which is causing null pointer expect(EmployeeInterfaceFactory.getAddressImpl()).andReturn(empAddress);

sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
  • "EmployeeInterfaceFactory" is in different package/dependency.. which I don't have control. Code change is not possible... – Balaji211 Jun 09 '21 at 06:40
  • empAddress=createMock(EmpAddress.class); is present in @Before method.. Is it not enough.. Please clarify – Balaji211 Jun 09 '21 at 06:52