【问题标题】:Using jUnit mock objects with Spring在 Spring 中使用 jUnit 模拟对象
【发布时间】: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


    【解决方案1】:

    您的测试不需要 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2018-03-09
      相关资源
      最近更新 更多