I have three classes A, B and C Where A is abstract class, B is also an abstract class and B extends A and C is non-abstract which extends B. I have variable by name AddressService addressService which is public in class B and is private in class A. I am writing a test case for class C which is non-abstract and calling method which is in class A and in class A i need to set the value of AddressService addressService variable which is used to invoke a method. AddressService is an interface which has methods and i am invoking one of the method in my super class A. Following is my code
public interface AddressService{
void test();
}
public abstract class A{
private AddressService addressService = (AddressService) ServiceLocatorBeanFactory.getService(AddressService.class);
public void createDocument(){
addressService . test();
}
}
public abstract class B extends A{
public AddressService addressService = (AddressService) ServiceLocatorBeanFactory.getService(AddressService.class);
}
public class C extends B {
}
Here is my test class
@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceLocatorBeanFactory.class})
public class createTest {
@SuppressWarnings("unchecked")
@Test
public void createTurnaroundDocument() throws Exception{
PowerMockito.mockStatic(ServiceLocatorBeanFactory.class);
AddressService addressService = Mockito.mock(AddressService.class);
PowerMockito.when(ServiceLocatorBeanFactory.getService(AddressService.class)).thenReturn(addressService);
C original = new C();
C handler = PowerMockito.spy(original);
handler.createDocument();
}
}
I tried setting the value of AddressService addressService present in class A which is abstract in multiple ways but still the value is null and i get NullPointer Exception.
Following are the different ways
1.Whitebox.setInternalState(handler, AddressService.class, addressService);
When i set this way the value is not set and is null and gives me NullPointerException
2.MemberModifier.field(A.class, "addressService").set(A.class, addressService);
When i set this way i get the following exception
java.lang.IllegalArgumentException: Can not set AddressService field A.addressService to java.lang.Class
3.Whitebox.setInternalState(A.class, AddressService.class, addressService);
When i set this way i get the following exception
org.powermock.reflect.exceptions.FieldNotFoundException: No static field assignable from "AddressService" could be found in the class hierarchy of A.
4.Whitebox.setInternalState(A.class, "addressService", addressService);
when i set this way i get the following exception
org.powermock.reflect.exceptions.FieldNotFoundException: No static field named "addressService" could be found in the class hierarchy of A.
Is there a way where we can set the value of private variable present in the super class using Mockito or PowerMockito. Please help
Aucun commentaire:
Enregistrer un commentaire