我真的没有选择。我正在尝试将实体保存到数据库并声明该值已被持久化。我在内存数据库中使用H2。
我不确定我做错了什么。每次运行我的应用程序时,我都会得到一个空值。
以下是我的课程:
CarRepositoryTest
@RunWith(SpringRunner.class)
@DataJpaTest(showSql= true)
public class CarRepositoryTest
{
@MockBean
private CarRepository repo;
@Test
public void saveTest() throws Exception {
Car car = new Car(1L, "MyFirstCar");
Car saved = repo.save(car);
assertNotNull(saved);
}
}
CarRepository
@Repository
public interface CarRepository extends CrudRepository<Car, Long>
{
}
application.properties
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.h2.console.enabled=true
spring.h2.console.path=/h2console
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
JpaTestApplication
@SpringBootApplication
@Configuration
@EnableJpaRepositories(basePackages="com.al.repository")
public class JpaTestApplication {
public static void main(String[] args) {
SpringApplication.run(JpaTestApplication.class, args);
}
}
答案 0 :(得分:1)
答案就像自动装配回购一样简单,而不是@SeanCarrol建议的MockBean
所以我的测试现在看起来像这样:
@RunWith(SpringRunner.class)
@DataJpaTest(showSql= true)
public class CarRepositoryTest
{
@Autowire
private CarRepository repo;
@Test
public void saveTest() throws Exception {
Car car = new Car(1L, "MyFirstCar");
Car saved = repo.save(car);
assertNotNull(saved);
}
}