[英]Spring Boot with spring-boot-starter-data-jpa in unit test needs mandatory @DataJpaTest
我正在測試Spring Boot功能,作為該領域的新手。 我有一個具有基本依賴性的簡單應用程序。
然后是帶有@SpringBootApplication
批注的簡單Application類。 然后,我有一個帶有@Service
批注的簡單DummyService。 然后,我使用一個@Test
方法以及@RunWith(SpringRunner.class)
和@SpringBootTest
批注創建了一個簡單的測試DummyServiceTest。
@SpringBootTest
是關鍵問題。 具有spring-boot-starter-data-jpa依賴性,此注釋測試甚至需要@DataJpaTest
注釋。 沒有它,即使測試不需要使用數據,該框架也無法解決HibernateJpaAutoConfiguration
或DataSource
或其他注入依賴項。
我能以某種方式抑制它嗎? 我不是任何一種Spring專家,所以我的猜測是可以通過一些簡單的配置來解決此問題。
PS好,回到樹上。 即使使用@DataJpaTest
,該測試也不能解決數據依賴性。 我嘗試添加@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
,它也不起作用。 我嘗試添加@Transactional
具有相同的結果。 這有點荒謬。
如果尚未使用JPA,請注釋掉/從build.gradle中刪除依賴項,直到使用JPA。 您需要先定義數據源和其他配置詳細信息,然后Hibernate和/或JPA配置才能成功完成。 @SpringApplicationConfiguration代碼運行時,即使您當前的“ hello world”測試不需要JPA數據,每個應用程序依存關系也會得到解決。
我當前的單元測試實際上已注釋掉@SpringBootTest。 這是在我的應用程序的JPA相關測試中如何設置和工作的簡化視圖:
@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');
}
}
接着
class UserHandshakeRepositoryIntegrationTest extends AbstractJpaTest {
@Autowired UserHandshakeRepoImpl handshakeRepository;
@Test
public void testSave() {
UserHandshake handshake = handshakeRepository.save(new UserHandshake());
assertThat(handshake.getId(), is(notNullValue()));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.