在IntegrationTest服务器和测试之间共享Spring上下文

时间:2016-01-12 17:34:19

标签: java spring-boot serenity-bdd

我正在尝试设置环境,以便我可以通过方法调用配置对象,然后使用HTTP请求对其进行测试,因此(半伪代码):

myStore.addCustomer("Jim")
HttpResponse response = httpClient.get("http://localHost/customer/Jim")
assertThat(response.status, is(OK))

(或在JBehave中)

Given a customer named Jim
When I make an HTTP GET to path "customer/Jim"
Then the response is 200 OK

我想使用Spring Boot来实现Web服务。

但是,我的尝试虽然看起来很干净,却无法正常工作,因为我的测试对象看到的Spring上下文与Web服务使用的Spring上下文不同。

我的环境是Serenity + JBehave,但我希望这些原则与直接jUnit没有什么不同。

我有:

@RunWith(SerenityRunner.class)
@SpringApplicationConfiguration(classes = Application.class )
@WebAppConfiguration
@IntegrationTest 
public class AcceptanceTestSuite extends SerenityStories {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private Store store;
}

...和应用程序代码:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

...以及我要分享的对象的类:

@Component
public class Store {

    private String id;

    private final Logger log = LoggerFactory.getLogger(Store.class);

    public Store() {
        log.info("Init");
    }

    public void addCustomer(String id) {
        this.id = id;
        log.info("Store " + this + " Set id " + id);
    }

    public String getCustomerId() {
        log.info("Store " + this + " Return id " + id);
        return id;
    }
}

...在我的控制器中:

@RestController
public class LogNetController {

    @Autowired Store store;

    @RequestMapping("/customer/{name}")
    public String read(name) {
        return ...;
    }

}

......在我的Serenity步骤课程中:

@ContextConfiguration(classes = Application.class)
public class TestSteps extends ScenarioSteps {

    @Autowired Store store;

    @Step
    public void addCustomer(String id) {
        store.addCustomer(id);
    }
}

当我运行测试时,服务器启动,setter运行,发出HTTP请求。但是

  • 我可以看到Store构造函数记录了两次“Init”:一个是由与测试关联的Spring上下文创建的,另一个是Spring属性,属于Tomcat容器。
  • 我可以看到SetReturn的不同实例都记录了Storeget。因此,我set的价值不是@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER return true; .... } return super.onOptionsItemSelected(item); }

如何让服务器和测试看到相同的Spring上下文?

0 个答案:

没有答案
相关问题