gpt4 book ai didi

java - JUnit Spring with xml No Annotation 加载bean失败

转载 作者:行者123 更新时间:2023-12-01 09:18:54 24 4
gpt4 key购买 nike

我在单元测试中总是得到一个空登录服务,使用带有 xml 配置的 spring,并且没有 Autowiring 。

除了 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 一起运行以使注入(inject)正常工作

您还应该使用@AutoWired注释属性loginService,并将xml中的bean重命名为loginService。

您的属性和 bean 名称必须相同,Spring 才会为您绑定(bind)它!

关于java - JUnit Spring with xml No Annotation 加载bean失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com