簡體   English   中英

帶有xml No Annotation的JUnit Spring無法加載bean

[英]JUnit Spring with xml No Annotation failed to load beans

我在單元測試中總是得到一個空登錄服務,使用的是帶有xml配置且沒有自動裝配的spring。

除了junit測試外,通過tomcat運行沒有任何錯誤。

我得到了junit-4.12,hamcrest-library-1.3,hamcrest-core-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;
    }
}

我相信您在課堂上缺少此注釋

@RunWith(SpringJUnit4ClassRunner.class)

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

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

Spring的屬性和bean名稱必須相同。

暫無
暫無

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

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