【问题标题】:@RunWith(JUnit4.class) + GrpcCleanupRule vs @RunWith(SpringJUnit4ClassRunner.class) + @Autowired@RunWith(JUnit4.class) + GrpcCleanupRule 与 @RunWith(SpringJUnit4ClassRunner.class) + @Autowired
【发布时间】:2021-06-22 05:23:55
【问题描述】:

我在测试 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 服务。

【问题讨论】:

    标签: java spring junit


    【解决方案1】:

    如果您需要使用不同的 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 现在扩展得更加优雅,或者您可以编写一个集成测试来启动应用程序并将某个配置文件应用于正在运行的应用程序以启用 stubbed beans/mock 集成等,以允许对应用程序进行更多的黑盒测试,以避免需要规则,因为规则在 Junit4 中非常有限

    【讨论】:

    • 我已经试过了。但是这些规则不知何故与@Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); 发生冲突,而且我在帖子中遇到了同样的例外。
    • 抱歉错过了,请参阅更新的示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2017-07-05
    • 2013-01-27
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多