user5412293
user5412293

Reputation:

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.

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

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

Upvotes: 0

Views: 2546

Answers (1)

user5412293
user5412293

Reputation:

The answer was as easy as autowiring the repo and not a MockBean as suggested by @SeanCarrol

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

Upvotes: 3

Related Questions