【发布时间】: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