Spring Test DBUnit does not create a dataset

2.2k views Asked by At

I use SpringBoot, Spring Test DBUnit. I wrote a test:

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));
}
}

And 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

But, when I try run my test, I have java.lang.NullPointerException. I guess this is because the database does not have the necessary records.

It can be seen from the log that he is trying to use a real database, not a test base. For some reason, it does not read my test configuration. enter image description here What am I doing wrong?

UPDATE:

When I write in ShortenerAppTest like this:

@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);
}
}

And It's work, but I still get an error in my LinkRepositoryTest

0

There are 0 answers