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

编程入门 行业动态 更新时间:2024-10-26 09:22:54
本文介绍了每次使用 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 进行测试后,模拟行为都会重置

本文发布于:2023-10-31 06:41:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545320.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:都会   进行测试   PowerMock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!