2016-10-28 95 views
0

我在單元測試中總是得到一個空登錄服務, 使用spring配置xml並且沒有自動裝配。JUnit Spring with xml沒有註釋未能加載bean

除了junit測試外,它在運行tomcat時沒有錯誤。

我得到的junit-4.12,hamcrest庫-1.3,hamcrest核-1.3

我的繼承人樣品的beans.xml

<util:properties location="classpath:user-credentials.properties" id="userCredentials"` /> 

<bean id="loginServiceBean" class="com.company.service.LoginService"> 
     <property name="userCredentials" ref="userCredentials" /> 
</bean> 
在我的JUnit測試

@ContextConfiguration("classpath:WEB-INF/beans.xml") 
public class LoginServiceTest { 

    private LoginService loginService; 

    @Before 
    public void setUp() throws Exception { 
    } 

    @After 
    public void tearDown() throws Exception { 
    } 

    @Test 
    public void loginTest() { 

     User user = createUserModel(); 
     try { 
      loginService.login(user); 
     } catch (LoginException e) { 
      fail(e.getMessage()); 
     } 

    } 

    private User createUserModel() { 
     User user = new User(); 
     user.setName("user"); 
     user.setPassword("pass"); 
     return user; 
    } 

    public LoginService getLoginService() { 
     return loginService; 
    } 

    public void setLoginService(LoginService loginService) { 
     this.loginService = loginService; 
    } 
} 
+0

'loginService'未初始化 – Danh

回答

1

我相信你在課堂上缺少這個註釋

@RunWith(SpringJUnit4ClassRunner.class) 

您必須告訴junit它應該與Spring一起運行以使注入工作

您還應該使用@AutoWired註釋屬性loginService,並將xml中的bean重命名爲loginService。

你的atrributes和bean的名字必須與Spring爲你綁定相同!