我用SpringBoot
, Spring Test DBUnit
。我写了一个测试:
ShortenerAppTest
:
@TestPropertySource(locations = "classpath:application-test.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ShortenerApp.class)
@WebAppConfiguration
public class ShortenerAppTest {
@Test
public void contextLoads() {
}
}
repositories/AbstractRepositoryTest
:
@TestPropertySource(locations = "classpath:application-test.properties")
@TestExecutionListeners(DbUnitTestExecutionListener.class)
@SpringBootTest(classes = ShortenerApp.class)
@DirtiesContext
abstract class AbstractRepositoryTest extends AbstractTransactionalJUnit4SpringContextTests {
}
repositories/LinkRepositoryTest
:
@DatabaseSetup(LinkRepositoryTest.DATASET)
@DatabaseTearDown(type = DatabaseOperation.DELETE_ALL, value = LinkRepositoryTest.DATASET)
public class LinkRepositoryTest {
final static String DATASET = "classpath:datasets/link-table.xml";
private final static Long LINK_1_ID = 100500L;
private final static String LINK_1_TEXT = "http://www.www.ya.ru";
@Autowired
LinkRepository repository;
@Test
public void findOneExisting() {
System.out.println(DATASET);
Optional<Link> got = repository.findOne(LINK_1_ID);
assertThat(got.isPresent(), equalTo(true));
Link linkFromDb = got.get();
Link link = new Link();
link.setId(LINK_1_ID);
link.setUrl(LINK_1_TEXT);
assertThat(linkFromDb, equalTo(link));
}
}
并且dataset
:
<?xml version="1.0" encoding="UTF-8" ?>
<dataset>
<links id="100500" url="http://www.ya.ru"/>
<links id="100501" url="http://www.mail.ru"/>
<links id="100502" url="http://www.google.com"/>
</dataset>
application-test.properties
:
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
但是,当我尝试运行测试时,我有java.lang.NullPointerException
. 我猜这是因为数据库没有必要的记录。
从日志可以看出,他是在尝试使用真实的数据库,而不是测试库。出于某种原因,它没有读取我的测试配置。 我究竟做错了什么?
更新:
当我这样写时ShortenerAppTest
:
@DatabaseSetup("/datasets/link-table.xml")
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
public class ShortenerAppTest {
@Autowired
LinkRepository repository;
@Test
public void contextLoads() {
Optional<Link> got = repository.findOne(100500L);
System.out.println(got);
}
}
它的工作,但我仍然得到我的错误LinkRepositoryTest