【发布时间】:2015-04-13 04:28:00
【问题描述】:
我是 Mockito junit 测试的新手,遇到了一个问题。如果你们能帮我解决这个问题,我将不胜感激。
class Activity{
Connection conn;
public SomeObject firstMethod() {
/* *some code* */
SomeObject obj = secondMethod();
return obj;
}
public SomeObject secondMethod(){
/* *some code* */
PreparedStatement ps = null;
try{
ps = conn.createStatement();
ps.setBytes(1, *someString*);
}catch(Exception e) { ... }
/* *some code* */
return someObject;
}
}
下面是我写的测试类。 secondMethod() 的单元测试完美运行。
class ActivityTest{
Activity activity;
@Before
public void setUp(){
activity = new Activity();
Connection conn = mock(Connection.class);
activity.setConnection(conn);
}
@Test
public void testSecondMethod(){
/* *works perfectly* */
}
@Test
public void testFirstMethod(){
SomeObject someObj = new SomeObject();
// *I get error on below line*
when(activity.secondMethod()).thenReturn(someObj);
SomeObject result = activity.firstMethod();
assertEquals(someObj, result);
}
}
我在 when(activity.secondMethod()).thenReturn(someObj) 上收到 NullPOinterException。当我跟踪错误堆栈时,空值是preparedStatement 对象ps。它发生在 secondMethod() 中的 ps.setBytes() 上。
我不明白这部分。为什么我会因为 ps 为空而得到异常。我为包含该代码的 secondMethod() 编写了一条规则。 我是否需要模拟 PreparedStatement obj.模拟所有内部对象也没有意义,因为我已经为它们所在的方法定义了规则。
你们能帮帮我吗?
谢谢
【问题讨论】:
标签: java unit-testing junit nullpointerexception mockito