首页 > 解决方案 > Cucumber 测试用例一起运行时失败,但单独运行时通过

问题描述

我正在将 SpringBoot 与 Cucumber 一起使用。一个特定的测试用例在一起运行时失败,在单独运行时通过。同一功能文件中的其他场景似乎工作正常。我尝试了以下链接,但它们不起作用。

现在我没有选择了。请帮忙。

功能文件:

Scenario Outline: To check if the service returns all the ids when more than 10000 Ids are returned by the query
Given sample request <payload>
 When the new end point is invoked
 Then the service returns <idCount> Ids

Examples: 
  | payload          | idCount | 
  | sample-payload-1 | 17575   | 
  | sample-payload-2 | 4       | 
  | sample-payload-3 | 23535   | 
  | sample-payload-4 | 34535   | 

步骤定义文件:

public class MyStepdefs extends AbstractStepsDefs {

@Autowired
MyController myController;

private String requestPayload;

private List<String> ids;

@Given("^sample request (.+)$")
public void sample_request_something(String payload) throws Throwable {
    this.requestPayload = payload;
}

@When("^the new end point is invoked$")
public void the_new_end_point_is_invoked() throws Throwable {
    String responseJSON = MyUtil.getPostResponseJSON(myController, "/ids", requestPayload);
    responseJSON = responseJSON.replace("[", "").replace("]", "").replaceAll("\"", "");
    ids = Arrays.asList(responseJSON.split(","));
}

@Then("^service returns list of available (.+)$")
public void service_returns_list_of_available_something(String ids) throws Throwable {
    List<String> list = Arrays.asList(ids.split(","));
    Assert.assertTrue(this.ids.containsAll(list));
}

@Then("^the service returns (.+) ids$")
public void the_service_returns_ids(String idCount) throws Throwable {
    System.out.println("Actual Size:" + this.ids.size());
    System.out.println("Expected Size:" + Integer.parseInt(idCount));
    Assert.assertEquals(this.ids.size(), Integer.parseInt(idCount));
}

@After
@Before
public void cleanUp() {
    ids = null;
}

}

现在我已经没有选择了。请帮忙。

UPDATE1: stepdef 类中 的第二个then块失败。sample-payload-1 和 sample-payload-2 通过,但另外两个失败。即使更改了样本有效负载的顺序,测试也会失败。

我得到的错误是一个断言错误,因为ids列表的大小不同。但是当我单独运行相同的测试时,由于大小匹配,我不会收到此错误。

标签: cucumbercucumber-javaspring-boot-test

解决方案


问题在于我用来循环通过触发查询并提取结果的逻辑的Instance 变量。counter第一个测试样本 [ sample-payload-1] 将单独工作,因为它具有实例的新副本counter。随后的样本将仅具有更改 counter后的值。

这解释了为什么测试用例在单独运行时通过,因为没有另一个测试会使用更改 counter后的.

修复:修复是在我退出实现/服务类之前重置counter回,以便后续请求将有一个新的0counter

经验教训:scope如果封闭类的 是 ,则永远不要依赖实例变量Singleton。每次调用类中的方法时,该值将不断变化


推荐阅读