简体   繁体   English

Spring Data Jpa保存测试失败

[英]Spring Data Jpa Save Test Fails

I am really out of options here. 我真的在这里没有选择。 I am trying to save an entity to the database and assert that the value has been persisted. 我正在尝试将实体保存到数据库并断言该值已持久。 I am using a H2 in memory database. 我在内存数据库中使用H2。

I am not sure what am I doing wrong. 我不确定我在做什么错。 Every time I run my application I get a null value back. 每次我运行应用程序时,我都会得到一个空值。

Here are my classes: 这是我的课程:

CarRepositoryTest 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 CarRepository

@Repository
public interface CarRepository extends CrudRepository<Car, Long>
{
}

application.properties 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 JpaTestApplication

@SpringBootApplication
@Configuration
@EnableJpaRepositories(basePackages="com.al.repository")
public class JpaTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(JpaTestApplication.class, args);
    }
}

The answer was as easy as autowiring the repo and not a MockBean as suggested by @SeanCarrol 答案就像自动装配存储库一样简单,而不是@SeanCarrol建议的MockBean

So my test looks like this now: 所以我的测试现在看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM