本文介绍了如何使用 spring 依赖注入模拟包的 util 类的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用 spring 依赖注入的包,使用以下代码进行单元测试.
I have a package using spring dependency injection for its unit tests using following code.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "<xml_location>" })
@WebAppConfiguration
我需要在 util 类中添加一个静态方法并需要模拟它以防止现有单元测试失败.我尝试使用 PowerMock,但遇到不同的错误,如下所示.
I need to add a static method in the util class and need to mock it to prevent existing unit tests to fail. I tried using PowerMock but getting different errors like the following ones.
<class_name> not prepared for test.
org.powermock.api.mockito.ClassNotPreparedException
Failed to load ApplicationContext
有人可以指出一个以前做过的例子吗?
Can someone please point to an example where this was done before?
推荐答案
您可以使用 Mockito.在最新版本中它有 Mockito.mockStatic()
方法.这是一个例子
You can use Mockito for that. In latest versions it has Mockito.mockStatic()
method.Here is an example
@Test
public void staticTest() {
MockedStatic<GoogleDriveHelper> staticMock = Mockito.mockStatic(GoogleDriveHelper.class);
staticMock.when(() -> GoogleDriveHelper.fixFileNameExtension(anyString(), anyString())).thenReturn("Blablabla");
assertEquals("Blablabla", GoogleDriveHelper.fixFileNameExtension("abc", "bcd"));
}
这篇关于如何使用 spring 依赖注入模拟包的 util 类的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!