I'm trying to do a test suite to check a @oneToMany relation i have
I have a book_category and a book but my issue is that i have several small tests inside a test class and it seems that the db (H2) is being deleted after each test
here is my code
@Slf4j
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(locations="classpath:test.properties")
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Autowired
private BookCategoryService categoryService;
@Test
@Order(1)
public void insertBookCategories() {
BookCategory cat1 = new BookCategory();
cat1.setCategoryCode(32);
cat1.setCategoryName("Category 1");
BookCategory cat2 = new BookCategory();
cat2.setCategoryCode(323);
cat2.setCategoryName("Category 2");
categoryService.save(cat1);
categoryService.save(cat2);
List<BookCategory> categories = categoryService.findAll();
assertEquals(2, categories.size());
log.debug("Executed test number 1");
}
@Test
@Order(2)
public void createBookWithCategory() {
Book book = new Book();
book.setDescription("Test Book");
book.setNumberOfSales(5);
book.setTitle("Test title");
BookCategory cat = categoryService.findByCategoryName("Category 2");
assertNotNull(cat); <------- this fails!!!!
assertEquals("Category 2", cat.getCategoryName());
book.setCategory(cat);
bookService.save(book);
log.debug("Executed test number 2");
}
@Test
@Order(3)
public void deleteCategoryWithBook() {
BookCategory cat = categoryService.findByCategoryName("Category 2");
assertEquals("Category 2", cat.getCategoryName());
categoryService.delete(cat);
log.debug("Executed test number 3");
}
@Test
@Order(4)
public void assertBookIsNotNull() {
Book book = bookService.findByTitle("Test title");
assertEquals("Test Book", book.getDescription());
assertNull(book.getCategory());
log.debug("Executed test number 4");
}
I get a null pointer when the code in test number 2 (createBookWithCategory) tries to fetch the category previously inserted in test 1
I tought that adding the @Transactional annotation would help persists the data until the entire test suite ends but its not working
here are my test.properties
h2.datasource.url=jdbc:h2:mem:somedatebase;DB_CLOSE_DELAY=-1
h2.datasource.username=sa
h2.datasource.password=
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create