I know of three options here
1. import.sql in Hibernate
It's as simple as adding an import.sql to your src/test/resources folder. Inside import.sql you can type in your sql to insert data you want. You would also have to set hibernate-ddl-auto to create in application.properties.
eg. Application.properties
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.url=jdbc:postgresql://localhost/asgard
spring.datasource.username=thor
spring.datasource.password=mjolnir
eg import.sql
insert into
account (id, createddate, modifieddate, password , username, disabled)
values (-1, now(),null, 'password','admin',false);
2. Spring Test DB Unit
Spring Test DB Unit is DB Unit specifically for Spring. This basically lets you add data and remove it after test on method as well as class level which is very useful. Check the link for more details. The xml actually makes it easier to manage the data you want to insert. You can also insert data programatically but it's more complicated and instructions should be there on the website.
@Test
@DatabaseSetup(value = "insert.xml")
@DatabaseSetup(connection="customerDataSource", value="insert-custs.xml")
public void testInsert() throws Exception {
// Inserts "insert.xml" into dataSource and "insert-custs.xml" into customerDataSource
// ...
}
eg insert.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<Person id="0" title="Mr" firstName="Phillip" lastName="Webb"/>
</dataset>
Table name is person along with id,title,firstName and lastName as fields.
3. Using @Before annotation
Using @Before annotation in Test class to set up db.
GenericTest Class
@RunWith(SpringRunner.class)
@SpringBootTest
public class GenericTest {
public EmployeeRepository employeeRepository;
@Before
public void setUp() {
employeeRepository.save(createRandomEmployeeObject());
}
@Test
public void insertSuccess(){
List<Employee> employee = employeeRepository.findAll();
//Logic to get employee from rest API
//Assert if data from rest API matches one in db
}
}