【问题标题】:JUnit test: null pointer exceptionJUnit测试:空指针异常
【发布时间】:2012-04-17 15:29:44
【问题描述】:

我正在使用带有 EXT JS 的 Spring 和 hibernate 来使用 tomcat 在网页上填充 EXT JS 表单...我使用访问数据库并返回我的 HQL 语句的方法填充表

现在我正在尝试执行一个简单的 JUnit 测试来计算返回的记录数,但是当我在填充 EXT JS 表单的 JUint 测试中调用该方法时,它返回此异常...我不知道为什么

JUnit 测试类

package com.fexco.helloworld.web;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.fexco.helloworld.web.dao.CustomerDaoImpl;
import com.fexco.helloworld.web.model.Customer;

/**
* Unit test for simple App.
*   /
public class CustomerServiceTest {

@Autowired
private CustomerDaoImpl customerDaoImpl;

@Test
public void findAllCustomersTest() {        
    List<Customer> list = customerDaoImpl.findAllCustomers();
    int numberInDatabase = list.size();
    assertEquals(5, numberInDatabase);
}

}

我访问数据库的方法

public List<Customer> findAllCustomers(){
    List<Customer> list = getHibernateTemplate().find("from Customer");
    return list;
}

和我的方法调用访问数据库的方法

public List<Customer> returnAllCustomers(){
    List<Customer> list = customerDaoImpl.findAllCustomers();
    return list;
}

您可以在此处看到使用与 junit(findAllCustomers()) 中相同的方法从数据库中填充项目的表单

有人有什么想法吗?

【问题讨论】:

    标签: spring hibernate spring-mvc extjs junit


    【解决方案1】:

    在 CustomerServiceTest 类之前添加以下行

    @RunWith(SpringJUnit4ClassRunner.class)  
    @ContextConfiguration(locations = { "file:src/main/resources/app-context.xml" })
     public class CustomerServiceTest {....
    

    其中 src/main/resources/app-context.xml - 是应用程序上下文的路径。很好,为测试创建单独的上下文。

    编辑

    您还需要在类路径中包含spring-test.jar。 对maven的依赖:

           <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring-version}</version>
            </dependency>
    

    【讨论】:

    • 您是否需要为 @RunWith(SpringJUnit4ClassRunner.class) 添加依赖项或其他内容,因为 eclipse 无法识别它
    【解决方案2】:

    您没有在单元测试中加载 Spring 上下文。

    您可以在此处查看 Spring 文档:http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/testing.html

    还有一个例子:Spring: JUnit-Test: applicationContext is not loaded

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多