【问题标题】:java.lang.NullPointerException: Cannot invoke method queryForList() on null objectjava.lang.NullPointerException:无法在空对象上调用方法 queryForList()
【发布时间】:2017-07-31 09:47:08
【问题描述】:

我在 Service 类中有一个简单的 getEmployeeList 方法,它使用 Spring JDBC 查询数据库以获取员工列表。

class EmployeeListService
{

private static final String QUERY_FOR_GETTING_ALL_EMPLOYEE_LIST="select ID, name from emp order by name";

     def dataSource
      private JdbcTemplate jdbcTemplate

     @PostConstruct
     def init() {
           jdbcTemplate = new JdbcTemplate(dataSource)
     }


    def getEmployeeList()  {

        ArrayList<String> employeeList = jdbcTemplate.queryForList(QUERY_FOR_GETTING_ALL_EMPLOYEE_LIST);
        return employeeList;
    }
}

我正在为 getEmployeeList 方法的 Null 检查编写 Grails 单元测试。

    @WithGMock
class EmployeeListServiceTest  extends GrailsUnitTestCase {

    EmployeeListService empService;

    @Before
    public void setUp() {
        empService = new EmployeeListService();

    }

    @Test
    public void toCheckgetEmployeeListDoesNotReturnNull()
    {
        ArrayList<String> employeeList = empService.getEmployeeList()

        assertNotNull(employeeList);
    }
}

当我以正常流程执行程序时,我得到了员工列表。但是当我执行单元测试时,我得到以下异常

 Failure:  toCheckgetEmployeeListDoesNotReturnNull(com.employee.home.service.EmployeeListServiceTest)

  java.lang.NullPointerException: Cannot invoke method queryForList() on null object
       at com.employee.home.service.EmployeeListService.getEmployeeList(EmployeeListService.groovy:170)
       at com.employee.home.service.EmployeeListServiceTest.toCheckgetEmployeeListDoesNotReturnNull(EmployeeListServiceTest.groovy:24)

【问题讨论】:

  • 所以,你的 jdbcTemplate 为空。
  • 这只是意味着 jdbcTemplate 为空。这是依赖问题!你在哪里创建 jdbcTemplate 对象?
  • 虽然我没有提到jdbcTemplate和datasource,但实际上我已经在服务类即EmployeeListService中创建了它们,理想情况下它不应该返回null
  • 我已经添加了上面缺少的代码。

标签: java unit-testing grails spring-jdbc


【解决方案1】:

在单元测试期间,您在 setUp 方法中手动创建服务实例时,不会调用 postConstruct 方法。

所以没有调用跟随。

 @PostConstruct
     def init() {
           jdbcTemplate = new JdbcTemplate(dataSource)
     }

这会导致您的 JdbcTemplate 在单元测试期间为空。

如果您需要测试数据库查询等,我建议您使用集成测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多