我有一个功能正在尝试通过 JUnit 进行测试,但我无法找到如何克服这个问题:
在服务中,我有这个声明:
Warning_Log Warning_Log_FRAGMENT = beanFactory.getBean(Warning_Log.class);
我尝试使用 @MockBean 注释在测试类中声明 beanFactory 对象,但我得到一个空指针异常。
最重要的是,我正在测试的函数是私有的,所以我使用反射来访问它。
你知道在junit测试函数中beanFactory(Warning_Log.class)是如何实现的吗?
编辑
服务中的代码如下:
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);
}
beanFactory 在服务中自动装配,如下所示:
@Autowired
private BeanFactory beanFactory;
编辑 2 这是我在 junit 函数中尝试导致空指针异常的方法:
Field bf = clazz.getClass().getDeclaredField("beanFactory");
bf.setAccessible(true);
bf.set(clazz, beanfactory);
beanfactory 在类的开头声明如下:
@MockBean
private BeanFactory beanfactory;
假设您有以下课程:
@Service
public class MyClass {
@Autowired
private BeanFactory beanFactory;
/*
* Some more code
*/
}
然后您想为该类创建一些单元测试,例如:
@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(...);
}
这是一般的想法。如果您有一个受依赖注入影响的字段,则不必使用反射来在单元测试中访问它。该MockBean
注释将告诉IoC容器来使用你的嘲笑类无论它被注入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句