簡體   English   中英

@RunWith(JUnit4.class) + GrpcCleanupRule 與 @RunWith(SpringJUnit4ClassRunner.class) + @Autowired

[英]@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) 但是當我使用它時,我所有的 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://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit4/rules/SpringClassRule.ZFC35FDC70D5FC69D236988A

這里有一個具體的例子。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM