简体   繁体   中英

JUnit Spring with xml No Annotation failed to load beans

i always getting a null login service in my unit testing, were using spring with xml configurations and no autowiring.

it got no error in running thru tomcat, aside from junit testing.

i got junit-4.12, hamcrest-library-1.3, hamcrest-core-1.3

heres my sample 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>

in my junit testing

@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;
    }
}

I believe you are missing this annotation in your class

@RunWith(SpringJUnit4ClassRunner.class)

You must tell to junit that it should run with Spring to get the injections working

You should also annote the property loginService with @AutoWired and rename the bean in xml to loginService.

Your atrributes and beans names must be the same for Spring bind it for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM