每次使用 PowerMock 进行测试后,模拟行为都会重置

时间:2022-11-01
本文介绍了每次使用 PowerMock 进行测试后,模拟行为都会重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 PowerMock 编写单元测试,模拟一些实用程序类的行为.为测试类定义一次行为(通过@BeforeClass 注解)原因:

I'm writing unit tests using PowerMock, mocking behaviour of some util classes. Defining behaviour once for test class (by @BeforeClass annotation) causes:

  • 第一次测试调用以返回模拟值
  • 第二次测试调用返回真正的方法返回值

示例代码:

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest( {A.class, B.class})
public class TestMockedMethods {

private static B b;

@BeforeClass
public static void setUp() {
    PowerMockito.mockStatic(A.class);
    PowerMockito.when(A.getVal()).thenReturn("X");

    b = PowerMockito.mock(B.class);
    PowerMockito.when(b.getVal()).thenReturn("Y");
}

@Test
public void test1() { // PASS
    Assert.assertEquals("X", A.getVal());
    Assert.assertEquals("Y", b.getVal());
}

@Test
public void test2() { // FAIL
    Assert.assertEquals("X", A.getVal()); // actual="A"
    Assert.assertEquals("Y", b.getVal()); // actual="B"
}

}
class A {
  static String getVal() {
    return "A";
  }
}
class B {
  String getVal() {
    return "B";
  }
}

知道第二次测试失败的原因吗?

Any ideas why second test is failing?

推荐答案

PowerMockito.mockStatic(...)方法调用MockCreator.mock(...).此方法注册一个 Runnable,将在 每次测试后执行:

The method PowerMockito.mockStatic(...) invokes MockCreator.mock(...). This method regsiters a Runnable that will be executed after each test :

MockRepository.addAfterMethodRunner(new MockitoStateCleaner());

这个runnable清除了Mockito的内部状态:

This runnable cleans the internal state of Mockito :

private static class MockitoStateCleaner implements Runnable {
    public void run() {
        clearMockProgress();
        clearConfiguration();
    }

    private void clearMockProgress() {
        clearThreadLocalIn(ThreadSafeMockingProgress.class);
    }

    private void clearConfiguration() {
        clearThreadLocalIn(GlobalConfiguration.class);
    }

    private void clearThreadLocalIn(Class<?> cls) {
        Whitebox.getInternalState(cls, ThreadLocal.class).set(null);
        final Class<?> clazz = ClassLoaderUtil.loadClass(cls, ClassLoader.getSystemClassLoader());
        Whitebox.getInternalState(clazz, ThreadLocal.class).set(null);
    }
}

所以你应该在每次测试之前执行你的设置.

So you should execute your setUp before each test.

@Before
public void setUp() {
    PowerMockito.mockStatic(A.class);
    PowerMockito.when(A.getVal()).thenReturn("X");

    b = PowerMockito.mock(B.class);
    PowerMockito.when(b.getVal()).thenReturn("Y");
}

这篇关于每次使用 PowerMock 进行测试后,模拟行为都会重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:使用模拟位置而不在设置中设置它 下一条:jmock 模拟静态方法

相关文章

最新文章