簡體   English   中英

Spring Boot 單元測試 - 測試失敗,抱怨沒有定義“entityManagerFactory”bean

[英]Spring Boot Unit Testing - Test fails complaining about not having an "entityManagerFactory" bean defined

我正在嘗試為 Spring Boot 應用程序中的控制器編寫單元測試。 該應用程序運行順利,我的問題是運行它的測試

下面是測試代碼:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@AutoConfigureTestEntityManager
public class MyControllerTest {

@Autowired
private MockMvc mockMvc;

@Mock
private MyRepository myRepository;

@Mock
ZendeskNotifier zendeskNotifier;

@Mock
ActivityLogger activityLogger;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void cannotSendFooWithoutMessageBody() throws Exception {
    this.mockMvc.perform(post("/api/v1/foo/1/send"))
            .andDo(print())
            .andExpect(status().is4xxClientError())
            .andExpect(content().string(containsString("The message body cannot be empty.")));
}
}

當我嘗試運行它時,我得到:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field jobEventRepository in foo.bar.util.memsource.svc.MemsourceEventProcessor required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

這讓我覺得很奇怪,因為我提供了AutoConfigureTestEntityManager注釋,並且希望所有與EntityManager相關的東西都到位。

如果Google將您帶到這里並且您使用的是Spring Boot,則可能需要將@DataJpaTest添加到測試類中。 它位於org.springframework.boot:spring-boot-test-autoconfigure 您還可以在重新運行時發現需要聲明對org.hibernate:hibernate-validator的依賴。

mockito測試類中注入Spring的TestEntityManager

@Autowired
private TestEntityManager entityManager;

您已在測試類上使用@AutoConfigureTestEntityManager來自動配置此測試實體管理器。 所以你不必在配置文件中做任何其他事情。

Spring Boot 正在加載您的應用程序的配置,導致您的數據層被初始化。

摘自 Spring Boot 的文檔, 檢測測試配置

每當您沒有明確定義一個時, Spring Boot 的 @*Test 注釋就會自動搜索您的主要配置。

搜索算法從包含測試的包開始工作,直到找到用@SpringBootApplication 或@SpringBootConfiguration 注釋的類。 只要您以合理的方式構建代碼,通常會找到您的主要配置。

當掃描命中您的main類時,它可能會找到像@EnableJpaRepositories這樣的注釋,它初始化您的數據層,因此需要實體管理器工廠。 (您也可能會看到其他副作用,例如 Hibernate 會初始化您的內存數據庫,如果您的應用程序使用的話。)

正如其他答案所建議的那樣,您可以初始化數據層,或者嘗試連接/模擬丟失的 bean。 但是由於您不是在此處測試數據層,因此最好控制測試的配置。

文檔提出了一些解決方案:

  1. @EnableJpaRepositories從主類移動到子包中的配置類。 它將被應用程序(從頂部包向下)掃描,但不會被單元測試掃描。 這在用戶配置和切片一節中討論。

  2. 添加嵌套的@Configuration類以覆蓋單元測試使用的配置。

第一個似乎是一般要遵循的好規則。 其他注釋如@EnableBatchProcessing@EnableScheduling可以以相同的方式處理,這將加快您的單元測試。

你需要配置entityManagerFactory ,你可以參考下面的代碼

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="org.demo.test.entity" />
<property name="dataSource" ref="dataSource" />

<property name="jpaProperties">
    <props>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.hbm2ddl.auto">create</prop>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    </props>
</property>

<property name="persistenceProvider">
    <bean class="org.hibernate.jpa.HibernatePersistenceProvider">
</bean>
</property>

</bean>

在子包中創建配置類

@Configuration
@EnableJpaRepositories(
    value = "com.company.repository"
)
public class JpaConfig {
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM