【问题标题】:Spring & Cucumber integration: @Sql import didn't executeSpring & Cucumber 集成:@Sql 导入未执行
【发布时间】:2016-08-24 10:51:31
【问题描述】:

我需要在练习中将黄瓜与春天结合起来。但是我不能用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!
  }

}

谢谢!

【问题讨论】:

    标签: spring testing cucumber


    【解决方案1】:

    @Sql 将由SqlScriptsTestExecutionListener 执行。 Spring SpringJUnit4ClassRunner 将注册所有TestExecutionListeners。

    来自SqlScriptsTestExecutionListenerjava 文档,它说:

    脚本和内联语句将在执行相应的测试方法之前或之后执行,具体取决于 executionPhase 标志的配置值。

    所以类级别 @Sql 等同于所有 @Testmethods 和单独的 @Sqlannotation。

    但是,当 cucumber 运行时,它不会执行任何@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"));
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2023-02-17
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      相关资源
      最近更新 更多