简体   繁体   中英

Spring Boot with spring-boot-starter-data-jpa in unit test needs mandatory @DataJpaTest

I'm testing Spring Boot capabilities as a newbie in this area. I have a simple app with basic dependencies.

  • sping-boot-starter-parent 1.5.7
  • sping-boot-starter
  • sping-boot-starter-data-jpa
  • sping-boot-starter-test

Then there is simple Application class with @SpringBootApplication annotation. Then I have a simple DummyService with @Service annotation. Then I have created a simple test DummyServiceTest with one @Test method and @RunWith(SpringRunner.class) and @SpringBootTest annotations.

@SpringBootTest is the key problem. With spring-boot-starter-data-jpa dependency and this annotation test requires even @DataJpaTest annotation. Without it the framework doesn't solve HibernateJpaAutoConfiguration or DataSource or other injection dependencies even if the test doesn't require using data.

Can I suppress it somehow? I'm not any kind of Spring guru so my guess is that there is some simple configuration to handle this problem.

PS Ok, back on trees. Even with @DataJpaTest that test doesn't solve data dependencies. I tried add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) and it doesn't work either. I tried add @Transactional with the same result. It's a little bit beyond ridiculous.

If you aren't using JPA yet, then comment out / remove the dependency from build.gradle until you are using JPA. You need to define a datasource and other configuration details before the Hibernate and/or JPA configuration will complete successfully. Every application dependency gets resolved while @SpringApplicationConfiguration code is running, even if your current "hello world" test doesn't require JPA data.

My current unit tests actually have @SpringBootTest commented out. Here's a simplified view of how things are set up and working in my app's JPA related tests:

@RunWith(SpringJUnit4ClassRunner)
@SpringApplicationConfiguration(classes = DaemonApplication)
@ActiveProfiles('local')
//@SpringBootTest
@Transactional
public abstract class AbstractJpaTest extends AbstractTransactionalJUnit4SpringContextTests { 
    @BeforeTransaction
    public void setupData() throws Exception {
        deleteFromTables('User', 'User_Session', 'User_Handshake');
    }
}

and then

class UserHandshakeRepositoryIntegrationTest extends AbstractJpaTest {

@Autowired UserHandshakeRepoImpl handshakeRepository;    


@Test
public void testSave() {
    UserHandshake handshake = handshakeRepository.save(new UserHandshake());
    assertThat(handshake.getId(), is(notNullValue()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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