java - Spring Data Jpa 保存测试失败

标签 java spring-data spring-data-jpa h2

我真的没有选择。我正在尝试将实体保存到数据库并断言该值已被持久化。我正在使用 H2 内存数据库。

我不知道我做错了什么。每次运行应用程序时,我都会得到一个空值。

这是我的类(class):

汽车存储库测试

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

最佳答案

答案就像 Autowiring 存储库一样简单,而不是像 @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);
    }
}

关于java - Spring Data Jpa 保存测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47501327/

相关文章:

java - 为什么我的绘图不能无循环地显示?

java - 读取字符串时遇到问题

java - Spring-Data-Jpa Repository - 实体列名上的下划线

spring - 将 PersistenceExceptionTranslationPostProcessor 与 Spring 的 JdbcTemplate 一起使用是否有意义?

java - 在 EclipseLink 上使用投影时出现 NotReadablePropertyException

java - Spring JPA/hibernate : use multiple projections on same query interface

java - SOAP-WS 安全 header 身份验证

JAVA:括号匹配方法不打印

java - 多路径之间的 QueryDSL 谓词绑定(bind) "or"

java - JPA 标准规范 - 使用 group by 进行多选返回所有列