在 JUnit 5 中,如何在所有测试之前运行代码 [英] In JUnit 5, how to run code before all tests

查看:57
本文介绍了在 JUnit 5 中,如何在所有测试之前运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@BeforeAll 注释标记在 中的所有测试之前运行的方法.

The @BeforeAll annotation marks a method to run before all tests in a class.

http://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

但是有没有办法在所有测试之前在所有类中运行一些代码?

But is there a way to run some code before all tests, in all classes?

我想确保测试使用一组特定的数据库连接,并且这些连接的全局一次性设置必须在运行任何测试之前发生.>

I want to ensure that tests use a certain set of database connections, and the global one-time setup of these connections must occur before running any tests.

推荐答案

现在可以通过创建自定义扩展在 JUnit5 中实现这一点,您可以从该扩展中在根测试上下文上注册关闭挂钩.

This is now possible in JUnit5 by creating a custom Extension, from which you can register a shutdown hook on the root test-context.

你的扩展看起来像这样;

Your extension would look like this;

import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL;

public class YourExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    private static boolean started = false;

    @Override
    public void beforeAll(ExtensionContext context) {
        if (!started) {
            started = true;
            // Your "before all tests" startup logic goes here
            // The following line registers a callback hook when the root test context is shut down
            context.getRoot().getStore(GLOBAL).put("any unique name", this);
        }
    }

    @Override
    public void close() {
        // Your "after all tests" logic goes here
    }
}

然后,您需要至少执行一次的任何测试类都可以使用以下注释进行注释:

Then, any tests classes where you need this executed at least once, can be annotated with:

@ExtendWith({YourExtension.class})

当你在多个类上使用这个扩展时,启动和关闭逻辑只会被调用一次.

When you use this extension on multiple classes, the startup and shutdown logic will only be invoked once.

这篇关于在 JUnit 5 中,如何在所有测试之前运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆