junit 重新加载类

发布于 2024-12-15 13:00:41 字数 916 浏览 1 评论 0原文

我使用 powermock 来模拟 Logger.getInstance() 方法。这会导致问题,因为 junit 似乎不会重新加载类,并且在第一个测试后测试类具有错误的记录器实例。

public class LoggedClass {
    public static Logger log = Logger.getInstance();
    ....
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({ LoggedClass.class, Logger.class })
public class SomeTests {
    private Logger log;
    @Before
    public void setUp() {
         PowerMockito.mockStatic(Logger.class);
         log = PowerMockito.mock(Logger.class);
         PowerMockito.when(Logger.getInstance()).thenReturn(log);

         PowerMockito.mockStatic(LoggedClass.class);
    }

    @Test
    public void firstTest() {
         assertTrue(LoggedClass.log == log);
    }

    @Test
    public void secondTest() { // fails
         assertTrue(LoggedClass.log == log);
    }
}

由于 LoggedClass 具有过时的日志实例,测试失败。我可以显式注入新的记录器实例,但是当有很多静态变量需要模拟时,这很麻烦。

如何设置 junit 在每次运行新测试时重新加载类?

I use powermock to mock Logger.getInstance() method. This causes a problem as junit seems not to reload classes and after the first test test class has wrong logger instance.

public class LoggedClass {
    public static Logger log = Logger.getInstance();
    ....
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({ LoggedClass.class, Logger.class })
public class SomeTests {
    private Logger log;
    @Before
    public void setUp() {
         PowerMockito.mockStatic(Logger.class);
         log = PowerMockito.mock(Logger.class);
         PowerMockito.when(Logger.getInstance()).thenReturn(log);

         PowerMockito.mockStatic(LoggedClass.class);
    }

    @Test
    public void firstTest() {
         assertTrue(LoggedClass.log == log);
    }

    @Test
    public void secondTest() { // fails
         assertTrue(LoggedClass.log == log);
    }
}

Test fails as LoggedClass has outdated log instance. I could inject explicitly new logger instance, but that is cumbersome when there are lots of static variables that needs to be mocked.

How can I set junit to reload classes every time it runs new test?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

屋檐 2024-12-22 13:00:41

第二个测试失败的原因是您在每个测试的 @Before 方法中创建了一个新的 log 实例,但自从调用了 Logger.getInstance( )静态,它只发生一次。考虑在 @BeforeClass 中执行 @Before 中的操作。

似乎没有理由为每个测试创建一个新的 log 实例。它是一个mock,因此只需重置即可。

The reason the second test fails is that you are creating a new instance of log in your @Before method for each test but since the call to Logger.getInstance() is static it is only happening once. Consider doing what you have in @Before in a @BeforeClass.

There does not seem to be a reason to create a new instance of log for each test. It is a mock and can therefore just be reset.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文