java - 从外部库访问 Spring applicationContext 或任何 bean
问题描述
我正在尝试将常见的 Cucumber 步骤定义从我们的 spring 应用程序移动到它自己的库中。这样我就可以跨多个服务重用相同的功能。
但是,要运行一些步骤定义,我需要访问应用程序上下文和 MockMvc。有没有办法将任何spring应用程序中的a 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);
这在春季应用程序中
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/bdd",
glue = {"com.my.library.etc"})
我假设我错过了弹簧如何扫描类路径的关键原则,但看不到它!
解决方案
如果您正在使用cucumber-spring
,您可以自动装配任何 bean,包括应用程序上下文到您的步骤定义中。步骤定义的位置无关紧要,只要它们在粘合路径上即可。
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
包中,您将使用以下方法同时包含两者:
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 {
}
注意:您还需要告诉 Cucumber 应该使用哪个类来引导您的应用程序上下文。这个类也应该在你的粘合路径上。例如:
import com.example.app;
import org.springframework.boot.test.context.SpringBootTest;
import io.cucumber.spring.CucumberContextConfiguration;
@CucumberContextConfiguration
@SpringBootTest(classes = TestConfig.class)
public class CucumberSpringConfiguration {
}
推荐阅读
- c# - 如何使用 UWP 应用检测由另一个应用触发的 Windows 10 Toast 通知
- java - 一段时间后重新启动kafka消费者时,如何解决“kafka-coordinator-heartbeat-thread”异常?
- c# - C# 命名冲突:我的类“Tag”与“object Control.Tag”冲突
- reactjs - Apexcharts反应条形边界半径4角?
- r - 根据选定的值更新 url
- c - 重置后使用相同的文件指针,但遇到问题
- c++ - 重载运算符&&它的返回类型
- python - Discord.py Bot 不播放音频
- asp.net-mvc - ASP.NET 会话锁定
- macos - MacOS/MacCatalyst 上的 RequestTrackingAuthorization