java - @RunWith(JUnit4.class) + GrpcCleanupRule 与 @RunWith(SpringJUnit4ClassRunner.class) + @Autowired
问题描述
我在测试 GRpcService 和从 SpringContext 获取 bean 时遇到问题。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {
Application.class},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class MainFlowTest3 {
@Rule
public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
@Autowired
private RouteService routeService;
@Autowired
private RouteRequestService routeRequestService;
@Autowired
private VehicleService vehicleService;
}
当我使用@RunWith(SpringJUnit4ClassRunner.class)时,我在测试 grpc 时遇到问题。我的例外是
java.lang.AbstractMethodError: Receiver class io.grpc.netty.NettyServerBuilder does not define or inherit an implementation of the resolved method abstract delegate()Lio/grpc/ServerBuilder; of abstract class io.grpc.internal.AbstractServerImplBuilder.
...
我找到了答案。我是因为我应该使用@RunWith(JUnit4.class)。但是当我使用它时,我所有的 Autowired bean 都是null。
如何在我的测试中结合这两种逻辑?我需要在一个测试中同时使用 @Autowired bean 和测试 grpc 服务。
解决方案
如果您需要使用不同的 Junit4 Runner,您可以执行以下操作,这将启用与 JUnit4 Runner 相同的功能,
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
可以在这里查看JavaDoc,
这里有一个具体的例子。
http://eddumelendez.github.io/blog/2015/08/01/spring-4-2-0-springclassrule-and-springmethodrule/
在您的情况下,您需要使用规则链,因为您有多个规则,
@Rule
public RuleChain chain= RuleChain
.outerRule(new SpringMethodRule())
.around(new GrpcCleanupRule());
另一种选择是尝试迁移到 JUnit5,因为它支持多个“规则”/Runners 现在扩展得更加优雅,或者您可以编写一个集成测试来启动应用程序并将某个配置文件应用于正在运行的应用程序以启用存根 bean /mock 集成等以允许对应用程序进行更多的黑盒测试以避免需要规则,因为规则在 Junit4 中非常有限
推荐阅读
- c# - 查找集合是否比 C# 中的元组列表更快、更优化?
- php - PHP 内存访问
- javascript - 动态生成的模态内部未验证的多个字段
- protractor - 将参数传递给 browser.get - 量角器
- c++ - Winsock - 两次接收数据包
- javascript - 获取数据并将数据转换为 CSV 并下载
- javascript - 当 div 重叠时使用混合混合模式更改文本颜色
- django - 如何确定获得 NoReverseMatch 的原因
- authentication - 使用 CloudFormation 在机器启动期间添加用户
- deployment - UWP:AppPackages 中的文件夹与包系列名称不同