【发布时间】:2015-05-26 19:05:58
【问题描述】:
我正在尝试为使用 Spring 的类编写单元测试。代码本身似乎很好,但由于某种原因,我的 When 语句中不断出现空指针异常。源码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-bean-config.xml"}
public class testClass {
@Mock TestPerson mockTestPerson;
private TestObject testObject;
@Before
public void setup() { testObject = new TestObject(); }
@Test
public void testGetFullName() throws Exception {
String firstname = "Bob";
String lastname = "Barker";
when(testPerson.getFirstName()).thenReturn(firstName); // Throws NullPointerException
when(testPerson.getLastName()).thenReturn(lastName); // I suspect this guy will do the same.
String result = testObject.getFullName(mockTestPerson);
assertNotNull(result);
}
}
TestPerson 类非常简单:
public class testPerson {
private String firstName;
private String lastName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName {
return this.LastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
最后是 TestObject 类。
public class TestObject {
public String getFullName(TestPerson testPerson) {
return testPerson.getFirstName + " " + testPerson.getLastName();
}
}
很简单,是吗?老实说,从测试中初始化一个 TestPerson 对象可能更容易。为了论证(而且我的其他需要使用 @Mock 的项目往往会产生同样的抱怨),我需要知道如何使用 @Mock 注释和 SpringJUnit4ClassRunner 正确模拟对象。
编辑:
所以我尝试直接在测试中创建一个新的 TestPerson 并设置名字和姓氏。奇怪的是,我仍然在同一行得到一个空指针异常。这是为什么?如果我无法创建或模拟对象,那么如何验证对象是否正常工作?
【问题讨论】:
标签: spring unit-testing spring-mvc intellij-idea junit