JUnit Mockito @InjectMock自动连接的Sessionfactory Bean

时间:2018-10-31 12:36:53

标签: java spring junit mockito autowired

我创建了一个特殊的applicationContext-test.xml,以将其用于我的测试类。

applicationContext-test.xml

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       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
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <context:property-placeholder location="classpath:db/database.properties"/>
    <context:annotation-config />


    <!--        DATASOURCE                      -->
    <jdbc:embedded-database id="h2dataSource" type="H2">
        <jdbc:script location="classpath:db/sql/create-db.sql" />
        <jdbc:script location="classpath:db/sql/insert-data.sql" />
    </jdbc:embedded-database>

    <!-- SESSION FACTORY -->
    <bean id="testSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="h2dataSource"/>
        <property name="packagesToScan" value="com.medkhelifi.tutorials.todolist.models.entities"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect"> ${hibernate.dialect} </prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!-- MUST have transaction manager, using aop and aspects  -->
    <bean id="testTransactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="testSessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="testTransactionManager" />
</beans>

现在,我想将testSessionFactory用作自动连线的Bean,并将其注入到模拟中。

TodoDaoTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration (value = "classpath:/conf/applicationContext-test.xml")
public class TodoDaoTest {

    @Autowired
    @Mock
    SessionFactory testSessionFactory;

    @InjectMocks
    TodoDao todoDao;


    private boolean mockInitialized = false;

    @Before
    public void setUp(){
        if(!mockInitialized) {
            MockitoAnnotations.initMocks(this);
            mockInitialized = true;
        }    
    }

    @Test
    public void getTodosByUserIdShouldNotReturnNull(){
        User user = new User();
        assertNotNull(todoDao.getTodosByUserId(user.getId()));
    }
}

这是我的TodoDao课程 TodoDao.java

@Component
@Transactional
public class TodoDao implements ITodoDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private AuthenticationFacade authenticationFacade;

    @Override
    @PostFilter("filterObject.userByUserId == authenticationFacade.getAuthenticatedFacade()")
    public List<Todo> getTodosByUserId(int userId) {
        List todos;
        // this is line 30
        todos = sessionFactory.getCurrentSession().createQuery("from Todo where userId = ?").setParameter(0, userId).list(); // this is line 30
        return todos;
    }
}

执行测试方法时,在第30行得到java.lang.NullPointerException at com.medkhelifi.tutorials.todolist.models.dao.TodoDao.getTodosByUserId(TodoDao.java:30)(如TodoDao.java类中所示) 我不知道我是否错过了什么。

1 个答案:

答案 0 :(得分:0)

您尚未定义sessionFactory模拟的行为。因此,当您的方法调用sessionFactory.getCurrentSession()时,它返回null并导致NullPointerException

在测试方法getTodosByUserIdShouldNotReturnNullsetUp方法中添加以下代码,此外,您还将需要几个模拟对象:

when(sessionFactory.getCurrentSession()).thenReturn(sessionMock); when(sessionMock.createQuery("from Todo where userId = ?")).thenReturn(queryMock);