在 Spring 中使用 jUnit 模拟对象

Using jUnit mock objects with Spring

我正在尝试为使用 Spring 的 class 编写单元测试。代码本身似乎没问题,但出于某种原因,我的 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 class 非常简单:

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 class。

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 方法。

@Before
public void initMocks() {
    MockitoAnnotations.initMocks(this);
}

详情见Mockito documentation