首页 > 解决方案 > @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 服务。

标签: javaspringjunit

解决方案


如果您需要使用不同的 Junit4 Runner,您可以执行以下操作,这将启用与 JUnit4 Runner 相同的功能,

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

可以在这里查看JavaDoc,

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit4/rules/SpringClassRule.html

这里有一个具体的例子。

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 中非常有限


推荐阅读