I'm trying to write a unit test for a class that uses Spring. The code itself seems to be fine, but I keep getting a null pointer exception on my When statements for some reason. The source code is as follows:
@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);
}
}
The TestPerson class is pretty simple:
public class testPerson {
private String firstName;
private String lastName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String lastName) {
this.lastName = lastName;
}
public String getLastName {
return this.LastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
And finally, the TestObject class.
public class TestObject {
public String getFullName(TestPerson testPerson) {
return testPerson.getFirstName + " " + testPerson.getLastName();
}
}
Simple, yes? To be honest, it might be easier to just create a TestPerson object from scratch. For argument's sake (and for the fact that my other projects that NEED to use @Mock tend to make the same complaints), I need to know how to properly mock object using the @Mock annotation AND SpringJUnit4ClassRunner.
Aucun commentaire:
Enregistrer un commentaire