junit - 如何将我的每个 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);
}
}
解决方案
推荐阅读
- python - 如何将 python pandas 系列列附加到数据框?
- javascript - 如何在 Javascript 中查找儒略历上的当前日期
- c# - .NET VS win表单项目中的序列化顺序(设计器代码)问题
- delphi - Indy TIdSocksServer 不转发流量
- python - Keras 中的 DirectoryIterator
- swift - 使用 uibezierPath 以垂直方式画线
- iframe - 带有 iframe 的 VSCode Webview - 无法查看 Webview 开发工具的 iframe dom
- java - Java 流将对象列表转换为所需的数据结构
- terraform - Terraform,如何将传入的字符串变量附加到一个值?
- javascript - 如何在指定列中下移单元格?谷歌表格