【问题标题】:Testing my UserService class, but need to mock a method that gets called at the same time测试我的 UserService 类,但需要模拟一个同时被调用的方法
【发布时间】:2012-11-26 11:07:18
【问题描述】:

我正在测试我的 userService 类方法,但我正在测试的方法调用了另一个方法。

@Test
public void testSomething() {
  HelloWorldResponse hwResponse = ....;

  expect(userDaoMock.helloWorldCall(....).andReturn(hwResponse);

  reploy();

  UserResponseCode response = userService.register(user);

  assertEquals(UserResponseCode.OK, response);
}

现在说我的注册方法调用了我的 userService 类中的另一个方法,我该如何模拟该调用?

据我了解,我不能这样做,因为我没有将整个 userService 类包装在一个模拟中吗?

更新

当我调试注册方法的 junit 测试时,我看到:

SomeThing thing = helloWorldCall(...);  // userService.helloWorldCall(...);

现在方法 helloWorldCall 只返回 userDao 返回的内容,我已经在我的测试中模拟了它,但由于某种原因,当我跟踪执行时它返回 null,所以 thing == null。

为什么是null,不应该是我的mock返回的值吗?

UserService#helloWorldCall 代码在下面,它再次简单地返回 userDao 返回的内容,正如您在上面看到的那样,它返回了我在单元测试中硬编码的响应。为什么我跟踪/调试单元测试时它为空?

public HelloWordResponse helloWorldCall(...) {
  return userDao.helloWorldCall(..)
}

【问题讨论】:

  • 如果方法也在 userService 中,为什么还需要模拟出方法?
  • @jeff 查看我的更新,即使我在模拟响应,返回值为 null。
  • 将 userDaoMock 连接到正在测试的 userService 的代码在哪里?

标签: java junit easymock


【解决方案1】:

它在这里杀死了范围,但是您可以使用 Spring 并使用不同的上下文。您的实际服务和您的模拟都实现了相同的接口。在您的测试中,您将连接模拟并在运行时连接实际的实现。

【讨论】:

    【解决方案2】:

    我正在使用模拟控件

    private IMocksControl mockMaker;
    

    所以我必须使用

    mockMaker.replay();
    mockMaker.verify();
    

    它现在可以工作了,因为我有许多不同的模拟对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-18
      • 2019-04-04
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2021-09-17
      相关资源
      最近更新 更多