Issue
I've a functioni'm trying to test via JUnit but I am not able to find how to overcome this issue:
in the service i have this declaration:
Warning_Log Warning_Log_FRAGMENT = beanFactory.getBean(Warning_Log.class);
I tried declaring the beanFactory object in the test class with the @MockBean annotation but i get a null pointer exception.
The cherry on top of the cake is that the function i'm testing is private so i'm using reflection to access it.
Do you know how the beanFactory(Warning_Log.class) can be implemented in the junit test function?
EDIT
the code in the service is the following:
try {
JSONObject jsonFragmentRequestWarning_Log = new JSONObject();
jsonFragmentRequestWarning_Log.put("messaggio", "Create Session Blocked [Assertion="+policy.getString("name")+"]|[flag_block_create_session="+gateway.flag_block_create_session+"]|[ApplicationName="+Request.getHeader("ApplicationName")+"]|[ErroreDaRitornare="+erroreDaRitornare+"]");
jsonFragmentRequestWarning_Log.put("sanitize", false);
Warning_Log Warning_Log_FRAGMENT = beanFactory.getBean(Warning_Log.class);
String sFragmentResponseWarning_Log = Warning_Log_FRAGMENT.warning_Log(jsonFragmentRequestWarning_Log.toString(), httpHeaders);
JSONObject jsonFragmentResponseWarning_Log = new JSONObject(sFragmentResponseWarning_Log);
}
the beanFactory is autowired in the service like so:
@Autowired
private BeanFactory beanFactory;
EDIT 2 This is what i tried in the junit function resulting in a null pointer exception:
Field bf = clazz.getClass().getDeclaredField("beanFactory");
bf.setAccessible(true);
bf.set(clazz, beanfactory);
And beanfactory is declared as follows at the beginning of the class:
@MockBean
private BeanFactory beanfactory;
Solution
Say that you have the following class:
@Service
public class MyClass {
@Autowired
private BeanFactory beanFactory;
/*
* Some more code
*/
}
And then you want to create some unit tests for that class, such as this:
@RunWith(SpringRunner.class)
public class MyClassTest {
@MockBean
private BeanFactory beanFactoryMock;
@Autowired
private MyClass myClass;
@Test
public void testMyClass() {
// Since we have annotated our BeanFactory with @MockBean
// this is now the instance that will be used by our class-under-test
Mockito.when(beanFactoryMock.getBean(Warning_Log.class))
.thenReturn(...);
}
This is the general idea. If you have a field that is subject to dependency injection you don't have to use reflection in order to access it in your unit tests. The MockBean
annotation will tell the IoC container to use your mocked class wherever it is being injected.
Answered By - Erik Karlstrand
Answer Checked By - David Goodson (JavaFixing Volunteer)