【发布时间】:2018-05-10 02:59:36
【问题描述】:
我在这里真的没有选择。我正在尝试将实体保存到数据库并断言该值已被持久化。我在内存数据库中使用 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);
}
}
汽车存储库
@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);
}
}
【问题讨论】:
-
您将@MockBean 与您的repo 一起使用,默认行为将返回null。假设您正在使用 h2,您可能想要一个真实的、非模拟的 repo。
-
@SeanCarroll 你是我的救星,我已经坚持了一段时间。我替换了 MockBean 和 Autowired 来创建实例,现在一切正常。 :) 非常感谢
-
您能否将此作为答案发布并接受或删除问题?没有这个,看起来这个问题仍然需要答案。
标签: java spring-data spring-data-jpa h2