Reputation: 3906
I have a class with private field
public class HibernateSessionFactoryManager{
private SessionFactory sessionFactory;
}
Now I want to do unit test of some method using the private field. So I was trying to access the private field using java reflection.
try {
Field field = HibernateSessionFactoryManager.class.getDeclaredField("sessionFactory");
field.setAccessible(true);
//field.set
SessionFactory sessionFactory = (SessionFactory) field.get(manager);
} catch (NoSuchFieldException e) {
System.out.println("no such");
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
I am getting
java.lang.NoSuchFieldException: sessionFactory at java.lang.Class.getField(Class.java:1584)
I am not able to figure out what mistake im doing. Any help will be appreciated.
Upvotes: 2
Views: 2222
Reputation: 617
For the benefit of those who encounter a similar issue with Mockito: When setting a private field using class.getDeclaredField()
, the object of which private field is to be set, must be instantiated directly using new
, not by calling Mockito's mock()
.
Upvotes: 3