java - Powermockito doNothing 用于带参数的方法

标签 java unit-testing powermock

我用 Java 开发了一个应用程序,我正在尝试使用 Powermockito 创建单元测试(我应该补充一点,我是单元测试的新手)。

我有一个名为 Resource 的类,它有一个名为 readResources 的静态方法:

public static void readResources(ResourcesElement resourcesElement);

ResourcesElement也是我编的。 在测试中,我想创建自己的资源,所以我希望上面的方法什么都不做。 我尝试使用此代码:

    PowerMockito.spy(Resource.class);
    PowerMockito.doNothing().when(Resource.class, "readResources", Matchers.any(ResourcesElement.class));

单元测试抛出异常:

org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)

Powermockito 还建议我应该在 when 之后使用 thenReturn 或 thenThrow,但似乎方法“when”在 doNothing 之后调用时返回 void(这是合乎逻辑的)。 如果我尝试:

PowerMockito.when(Resource.class, "readResources", Matchers.any(ResourcesElement.class)).....

doNothing 不是什么时候之后的选项。

我设法使没有参数的方法不做任何事情,使用该方法的 2 个参数版本。例如:

PowerMockito.doNothing().when(Moduler.class, "startProcessing");

这有效(startProcessing 不接受任何参数)。

但是我怎样才能让那些接受参数的方法对 Powermockito 什么都不做呢?

最佳答案

您可以在下面找到一个功能齐全的示例。由于您没有发布完整的示例,我只能假设您没有使用 @RunWith@PrepareForTest 注释测试类,因为其余部分似乎没问题。

@RunWith(PowerMockRunner.class)
@PrepareForTest({Resource.class})
public class MockingTest{

    @Test
    public void shouldMockVoidStaticMethod() throws Exception {
        PowerMockito.spy(Resource.class);
        PowerMockito.doNothing().when(Resource.class, "readResources", Mockito.any(String.class));

        //no exception heeeeere!
        Resource.readResources("whatever");

        PowerMockito.verifyStatic();
        Resource.readResources("whatever");
    }

}

class Resource {
    public static void readResources(String someArgument) {
        throw new UnsupportedOperationException("meh!");
    }
}

关于java - Powermockito doNothing 用于带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22981048/

相关文章:

java - 当模式中有相同的表时,如何在运行时动态传递模式名称

unit-testing - 单元测试逻辑、集成测试数据

java - AnyString() 作为单元测试的参数

unit-testing - Grails中的Micronaut声明式客户端:如何模拟它?

java - 在最终(实用程序)类中模拟私有(private)静态方法

java - MockClassLoader无法访问jdk/internal/reflect父类(super class)jdk.internal.reflect.MagicAccessorImpl

java - 这些访问Java中其他类的方法有什么区别?

java - 如何从Java中的命令行获取变量?

java - 如何在android项目上运行java类?

python - `py.test` 和 `__init__.py` 文件