【问题标题】:Nullpointerexception EasyMock when testing Controller测试Controller时出现Nullpointerexception EasyMock
【发布时间】:2017-12-12 13:08:16
【问题描述】:

我想测试我的控制器类及其方法。

我的控制器方法如下所示:

@RequestMapping(value = "/updateUserStory/{usid}", method = RequestMethod.GET)
public String updateUserStory(@PathVariable("trrid") Integer trrID, @PathVariable("usid") Integer userstoryID, Model model ){
    UserStory userStory = this.userStoryService.getUserStoryById(userstoryID);

    model.addAttribute("userstory", userStory);
    model.addAttribute("trrID", trrID);

    return "updateUserStory";
}

我的测试方法如下:

public void updateUserStory() throws Exception {
    Model model = mockModel();

    UserStory userStory = new UserStory();
    userStory.setId(1);

    EasyMock.expect(userStoryService.getUserStoryById(1)).andReturn(userStory);
    EasyMock.replay(userStoryService);

    String test = controller.updateUserStory(1, 1, model );

    EasyMock.verify(userStoryService);

    Assert.assertEquals("updateUserStory", test);
}

我在上面为userStoryService 添加了@Mock

@Mock
private UserStoryServiceImpl userStoryService;

和@TestSubject 为UserStoryController(在测试中简称为控制器)。

@TestSubject
UserStoryController controller = new UserStoryController();

在运行测试时,我不断在 EasyMock.expect 行得到 A NullPointerException。我不知道这是怎么失败的。我在嘲笑正确的方法。

【问题讨论】:

  • userStoryService 是如何初始化的?
  • @NimrodArgov 添加了那部分
  • 控制器类如何访问userStoryService?你传进去吗? controller 是在哪里创建的?
  • 据我了解,当您 @Mock 一个类时 EasyMock 会自动模拟来自该类的调用
  • 你的控制器类是否有 UserStoryServiceImpl 的设置器?

标签: java unit-testing easymock


【解决方案1】:

我看到两个可能的原因。

1.您没有使用任何跑步者或规则。

要注入模拟,EasyMock 需要一个 JUnit 规则

@Rule
public EasyMockRule mocks = new EasyMockRule(this);

或跑步者

@RunWith(EasyMockRunner.class)
public class MyTest {

2。字段类型为UserStoryService

不是UserStoryServiceImpl。所以你应该模拟UserStoryService。

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2021-01-25
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2021-06-18
    相关资源
    最近更新 更多