在Spring中使用jUnit mock对象

时间:2015-05-26 19:05:58

标签: 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 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并设置名字和姓氏。奇怪的是,我仍然在同一行得到一个空指针异常。这是为什么?如果我无法创建或模拟对象,那么如何验证对象是否正常工作?

1 个答案:

答案 0 :(得分:2)

您的测试不需要Spring。您应该删除这两个注释

printf(" \t\b\b\b\b\b\b");

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/spring-bean-config.xml"} 注释本身没有做任何事情。你必须创建模拟。这可以使用规则

来完成
@Mock

@Rule public MockitoRule rule = MockitoJUnit.rule(); 方法。

@Before

有关详细信息,请参阅Mockito documentation