2017-03-03 75 views
-1

我創建了一個簡單的RestController,它自動裝載了EntityManager和我擁有的其他類。如果我運行我的應用程序,一切正常,自動線被定義。現在,我想爲我的類來創建一個簡單的測試:Autowire不能在Spring測試中工作

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@EnableWebMvc 
@ContextConfiguration(classes = MonitoringController.class) 
public class MonitoringControllerTest { 

    private MockMvc mockMvc; 

    @Autowired 
    WebApplicationContext wac; 

    @Before 
    public void setup() {mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 

    } 

    @Test 
    public void testMonitoringIsUp()throws Exception { 
     mockMvc.perform(get("/monitoring")) 
       .andExpect(status().isOk()); 
    } 

這裏開始的問題,我收到提示 產生的原因:org.springframework.beans.factory.UnsatisfiedDependencyException:錯誤名稱創建豆「 monitoringController':通過字段'em'表示的不滿意的依賴關係;嵌套異常是org.springframework.beans.factory.NoSuchBeanDefinitionException:沒有提供可用的'javax.persistence.EntityManager'類型的限定bean:預計至少有1個符合自動佈線候選者的bean。依賴註釋:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

我想我錯過了一件很簡單的事情。任何幫助讚賞。

回答

0

找到解決方案。添加了@EnableAutoConfiguration,它負責處理EntityManager問題。

+0

你在哪裏添加此? – milosmns

0

檢查您使用的彈簧版本。在春季啓動的1.4.x及以上 所有你需要的是:

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class MonitoringControllerTest { 
    // autowire beans and perform tests with @Test 
} 

閱讀本spring boot tests improvments