数据库
首页 > 数据库> > Spring&Cucumber集成:@Sql导入未执行

Spring&Cucumber集成:@Sql导入未执行

作者:互联网

在实践中,我需要将黄瓜与春天融合在一起.但是我无法使用spring的@Sql注释导入一些测试数据.但是,其他不使用黄瓜的集成测试也可以正常工作.我没找到原因?黄瓜赛跑者:

@RunWith(Cucumber.class)
@CucumberOptions(features={"classpath:features/"})
public class CucumberIT {

}

和步骤定义:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes={DevDbConfig.class})
@Sql("classpath:test-reader-data.sql")
@Transactional
@ActiveProfiles("dev")
public class StepDefines {

  @Autowired
  ReaderService readerService;

  Reader reader;

  @Given("^a user with name Lily$")
  public void a_user_with_name_Lily() throws Throwable {
    reader = readerService.findByName("Lily"); // reader is null here!
  }

  @Given("^this user Lily exists$")
  public void this_user_Lily_exists() throws Throwable {
      assertThat(reader, notNullValue());
  }

  @Then("^Lily's info should be returned$")
  public void lily_s_info_should_be_returned() throws Throwable {
      assertThat(reader.getName(), is("Lily"));
  }

}

但是以下测试代码可以正常导入测试数据:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes={DevDbConfig.class})
@Sql("classpath:test-reader-data.sql")
@Transactional
@ActiveProfiles("dev")
public class ReaderServiceTest {

  @Autowired
  ReaderService readerService;

  @Autowired
  EntityManager entityManager;

  @Test
  public void testQueryByIdAndShouldNotReturnNull() {    
    Reader reader = readerService.findByName("Lily");
    assertThat(reader, notNullValue()); // reader is not null!
  }

}

谢谢!

解决方法:

@Sql将由SqlScriptsTestExecutionListener执行. Spring SpringJUnit4ClassRunner将注册所有TestExecutionListener.

SqlScriptsTestExecutionListenerjava文档中说:

Scripts and inlined statements will be executed before or after execution of the corresponding test method, depending on the configured value of the executionPhase flag.

因此,一个类级别的@Sql等效于具有单独@Sqlannotation的所有@Testmethods.

但是,当黄瓜运行时,它将不会执行任何@Test方法,并且@Sql没有机会执行.

最后,我必须自己做:

  @Autowired
  DataSource ds;

  @Given("^a user with name Lily$")
  public void a_user_with_name_Lily() throws Throwable {
    ScriptUtils.executeSqlScript(ds.getConnection(), new ClassPathResource("test-reader-data.sql"));
    reader = readerService.findByName("Lily");
  }

  @Given("^this user Lily exists$")
  public void this_user_Lily_exists() throws Throwable {
    assertThat(reader, notNullValue());
  }

  @Then("^Lily's info should be returned$")
  public void lily_s_info_should_be_returned() throws Throwable {
    assertThat(reader.getName(), is("Lily"));
  }

标签:testing,cucumber,spring
来源: https://codeday.me/bug/20191118/2026781.html