java - 有没有办法使用 EasyMock 部分模拟一个对象?

标签 java testing mocking easymock

例如假设我有这门课:

public class Foo Implements Fooable {
  public void a() {
    // does some stuff
    bar = b();
    // moar coadz
  }
  public Bar b() {
    // blah
  }
  // ...
}

我想测试 Foo.a。我想模拟 Foo.b,因为我正在单独测试该方法。我想象的是这样的:

public class FooTest extends TestCase {
  public void testA() {
    Fooable foo = createPartialMock(
      Fooable.class,  // like with createMock
      Foo  // class where non-mocked method implementations live
    );

    // Foo's implementation of b is not used.
    // Rather, it is replaced with a dummy implementation
    // that records calls that are supposed to be made;
    // and returns a hard coded value (i.e. new Bar()).
    expect(foo.b()).andReturn(new Bar());

    // The rest is the same as with createMock:
    //   1. Stop recording expected calls.
    //   2. Run code under test.
    //   3. Verify that recorded calls were made.
    replay(foo);
    foo.a();
    verify(foo);
  }
}

我知道我可以编写自己的 Foo 子类来为我做这类事情。但如果不是必须的话,我不想这样做,因为这很乏味,即应该自动化。

最佳答案

在 EasyMock 3.0+ 中,您可以使用 mockbuilder 创建 Partial mock

EasyMock.createMockBuilder(class).addMockedMethod("MethodName").createMock();

关于java - 有没有办法使用 EasyMock 部分模拟一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10825284/

相关文章:

java - libgdx 不会绘制 Sprite 或动画

java - 如何在Java套接字编程中解析index.html文件中包含的style.css的路径

java - 如何检查搜索框文本是否与链接匹配?

service - Karma/Jasmine 使用依赖项对 AngularJS 服务进行单元测试

asp.net-mvc - 如何模拟 ServiceStackController Cache 属性?

Java:简单的递归函数只返回 1

java - 如何在服务器上编译我的服务器代码?

c++ - 谷歌模拟 : Mocking parent class?

java - JMeter 示例响应编码

python - Selenium (Python)+ react