首页 > 解决方案 > 如何将我的每个 Junit 5 测试作为特权操作运行?

问题描述

我正在使用 Junit 5 编写集成测试。我应该使用特权操作(作为登录用户)运行每个测试。

我可以通过使用 Subject.doAs 从每个测试中调用来实现它,如下所示:

Subject.doAs(systemSubject, (PrivilegedAction<Object>) () -> actualMethodToBeTested();

但是有没有办法通过在 Junit 5 中使用 Extension 来实现这一点?原因是避免在每个方法中调用 Subject.doAs。

在 Junit 4 中,我可以使用测试装饰器和运行器来实现它。

我的 Junit 4 跑步者的简化版本:


@Override
public void run(RunNotifier notifier) {
        try {
            Object testObject = testClass.newInstance();
            for (Method method : testClass.getMethods()) {
                if (method.isAnnotationPresent(Test.class)) {
                    notifier.fireTestStarted(Description
                            .createTestDescription(testClass, method.getName()));
                    final Subject systemSubject = getSystemSubject();
                    Subject.doAs(systemSubject, (PrivilegedAction<Object>)
                                            () -> {
                                                try {
                                                    return method.invoke(testObject);
                                                } catch (IllegalAccessException e) {
                                                    return null;
                                                } catch (InvocationTargetException e) {
                                                    return null;
                                                }
                                            });

                    notifier.fireTestFinished(Description
                            .createTestDescription(testClass, method.getName()));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

标签: junitjunit5

解决方案


推荐阅读