有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java@RunWith(JUnit4.class)+GrpcCleanupRule vs@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)。 但是当我使用它时,我所有的自动连线bean都是空的

我如何在测试中结合这两种逻辑?我需要@Autowired bean和在一次测试中测试grpc服务


共 (1) 个答案

  1. # 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,因为它支持多个“规则”/“Runner”扩展,现在扩展得更加出色,或者,您可以编写一个集成测试来加速应用程序,并对正在运行的应用程序应用特定的配置文件,以启用存根bean/模拟集成等,从而允许对应用程序进行更多的黑盒测试,以避免需要规则,因为Junit4中的规则非常有限