从外部库访问Spring applicationContext或任何bean

问题描述 投票:0回答:1

我正在尝试将常见的Cucumber步骤定义从我们的spring应用程序移到其自己的库中。这样,我可以在多个服务中重用相同的功能。

但是,要运行某些步骤定义,我需要访问应用程序上下文和MockMvc。有没有一种方法可以将任何Spring应用程序中的bean自动连接到我的库中?

我已经在库中尝试了以下内容

@SpringBootTest(classes = StepDefinitonConfig.class)
@AutoConfigureMockMvc
public class StepDefinitonConfig {

    @Autowired
    protected MockMvc mockMvc;

    @Autowired
    protected ApplicationContext applicationContext;
}

mockMvc.perform(post(url/here)...
MockWebServiceClient mockWs = MockWebServiceClient.createClient(applicationContext);

并且在Spring应用程序中此

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/bdd",
        glue = {"com.my.library.etc"})

我假设我缺少弹簧如何扫描类路径的关键原理,但是看不到!

java spring-boot cucumber-java
1个回答
0
投票

如果使用cucumber-spring,则可以将包括应用程序上下文在内的任何bean自动连接到步骤定义中。只要步定义在胶合路径上,都无所谓。

cucumber-spring

因此,如果您的某些步骤定义在package com.example.lib; public class MyStepDefinitions { @Autowired private MyService myService; @Given("feed back is requested from my service") public void feed_back_is_requested(){ myService.requestFeedBack(); } } 程序包中,而某些在com.example.lib程序包中,则可以通过以下方式将它们都包括在内:

com.example.app

注意:您还需要告诉Cucumber应该使用哪个类来引导应用程序上下文。此类也应该在您的胶粘路径上。例如:

package com.example;

import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(glue = {"com.example.app", "com.example.lib"})
public class RunCucumberTest {
}
© www.soinside.com 2019 - 2024. All rights reserved.