在Spring中使用jUnit模拟对象
我试图为一个使用Spring的类编写一个单元测试。代码本身似乎很好,但出于某种原因,我的When语句上不断出现空指针异常。源代码如下:在Spring中使用jUnit模拟对象,spring,unit-testing,spring-mvc,intellij-idea,junit,Spring,Unit Testing,Spring Mvc,Intellij Idea,Junit,我试图为一个使用Spring的类编写一个单元测试。代码本身似乎很好,但出于某种原因,我的When语句上不断出现空指针异常。源代码如下: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/spring-bean-config.xml"} public class testClass { @Mock TestPerson mockTestPerson; private TestOb
@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。您应该删除这两个注释
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-bean-config.xml"}
@Mock
注释本身没有做任何事情。您必须创建模拟。这可以使用规则来完成
@Rule
public MockitoRule rule = MockitoJUnit.rule();
或通过方法之前的
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
有关详细信息,请参阅