简体   繁体   中英

Unable to load beans from Application Context in junit test

I'm trying to implement a group of tests for my app. In this case, I have some mybatis mappers whose beans are defined in my applicationContext.xml. For example:

<bean id="usersMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.myapp.dao.UserMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean> 

I've been looking for hours how to implement junit tests properly because some internet posts are deprecated or not up to date. This is my junit class actually:

@ContextConfiguration(locations = {"classpath:*applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class GroupTest {


    @Autowired
    ApplicationContext context;

    @Test
    public void testCreateGroup() throws SQLException {
        UserMapper um = (UserMapper)context.getBean("usersMapper");  
    }
}

There are no errors during the startup. When I try to get the bean usersMapper returns an exception (There is no bean definition..) Maybe, is not loading the properly applicationContext?

I also tried Mockito with no success. I've read it does cool things, but is it capable of loading the context as well as Spring? When I call the getUsers method from UserMapper, it returns null. This is my implementation:

@ContextConfiguration(locations = {"classpath:*applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class GroupTest {


    @Mock
    private UserMapper userMapper;


    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }


    @Test
    public void testCreateGroup() throws SQLException {
        userMapper.getUsers(); 
    }
}

For the record... my applicationContext.xml is placed in /src/main/webapp/WEB-INF/applicationContext.xml Hope you can guide me the right way. Thank you

Edit1: applicationContext.xml and context.xml added:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:comp/env/jdbc/adminDB"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="/WEB-INF/mybatis-config.xml" /> 
    </bean> 

    <bean id="usersMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="es.unican.meteo.dao.UserMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean> 

</beans>

It seems that Peter Hart solution loads the applicationContext.xml but a new problem appears. I need to use a jndi Resource in my app (reference included in applicationContext.xml). Is this no possible in test environment? The exception shows the following:

Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial 

This is my context.xml

<Context>
    <Resource name="jdbc/adminDB" auth="Container" type="javax.sql.DataSource"
             maxActive="20" maxIdle="10" username="***" password="***"
             driverClassName="org.apache.derby.jdbc.ClientDriver"
             url="jdbc:***"/>
</Context>

The problem is that you've requested a classpath resource, and WEB-INF/applicationContext.xml is probably not on the classpath (it usually wouldn't be).

You could try moving the applicationContext.xml to somewhere on the classpath. I'm guessing that you are using maven, in which case, this would usually either be src/main/resources , or src/test/resources (if this is specific to a particular test, rather than a 'real' application context file). I would also fix your @ContextConfiguration as @ohiocowboy suggests (assuming you put it directly in that directory, as things will generally work better if you're explicit about the location).

If your application context absolutely needs to be in WEB-INF/applicationContext.xml , you might try using file:src/main/webapp/WEB-INF/applicationContext.xml . If you run from the base directory of the project with mvn test , it should work, and it would probably work from the eclipse test runner also (no idea about Idea or NetBeans, but my guess is that it might work).

Your application context is not being loaded properly. The locations attribute of the @ContextConfiguration annotation should be "classpath:main/webapp/WEB-INF/applicationContext.xml" , "classpath:**/applicationContext.xml" or "classpath*:applicationContext.xml" . When you run the test, the application is not deployed, hence WEB-INF will not be in the classpath(unless you have added it to the test classpath yourself).

When using a mock object, you need to provide mock implementations for the methods that are going to be called. The getUsers() method is returning null because you have not set the desired result. You can check the mockito website for examples at http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html .

try

@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})

UPDATE Actually that doesn't work either because. The applicationContext.xml isn't on the classpath. It needs to be moved into the WEB-INF/classes directory.

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