首页 > 解决方案 > 从外部库访问 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"})

我假设我错过了弹簧如何扫描类路径的关键原则,但看不到它!

标签: javaspring-bootcucumber-java

解决方案


如果您正在使用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 {

}

推荐阅读