【问题标题】:How to mock a static method of util class of a package using spring dependency injection如何使用spring依赖注入模拟包的util类的静态方法
【发布时间】:2021-06-11 08:13:45
【问题描述】:

我有一个使用 spring 依赖注入的包,它使用以下代码进行单元测试。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "<xml_location>" })
@WebAppConfiguration

我需要在 util 类中添加一个静态方法,并且需要对其进行模拟以防止现有的单元测试失败。我尝试使用 PowerMock,但遇到以下错误。

<class_name> not prepared for test.
org.powermock.api.mockito.ClassNotPreparedException
Failed to load ApplicationContext

有人可以指出一个以前做过的例子吗?

【问题讨论】:

    标签: java spring unit-testing mocking powermock


    【解决方案1】:

    您可以为此使用 Mockito。在最新版本中,它具有Mockito.mockStatic() 方法。 这是一个例子

    @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"));
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-02
      • 2020-06-06
      • 2015-06-06
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多