2016-08-24 61 views
2

我需要在實踐中整合黃瓜與春季。但是我不能用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! 
    } 

} 

謝謝!

回答

2

@Sql將由SqlScriptsTestExecutionListener執行。春季SpringJUnit4ClassRunner將註冊所有的TestExecutionListener s。

SqlScriptsTestExecutionListener Java文檔,它說:

腳本和內嵌語句將之前或相應的測試方法的執行之後,這取決於executionPhase標誌的配置的值來執行。

因此,一個一流水平@Sql相當於所有@Test方法與個別@Sql註解。

但是,當黃瓜運行時,它不會執行任何@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")); 
    }