如何使用EasyMock模拟另一种方法调用的方法?

时间:2016-12-02 12:07:52

标签: java easymock

我需要在void方法中模拟一个方法。

以下是我的示例代码:

centerY

现在,在我的测试课中,我想模仿class MyClass { public MyClass(Session s, Boolean b1, Boolean b2) void myMethod(some paramaters...) { // some code int count= setSize(); } int setSize() { // some calculation.... return size; } 以返回我自己的值setSize()

我确实喜欢:

300

致电MyClass mockclass = createNiceMock(MyClass.class); EasyMock.expect(mockimplyZero.setBatchSize()).andReturn(Integer.valueOf(300)); mockclass.myMethod(parameters....) 时,它无法正确进入该方法。 我认为可能是EasyMock正在为myMethod构造函数设置默认值。如何正确地进行模拟?

MyClass除了构造函数MyClassmyMethod

之外没有方法

2 个答案:

答案 0 :(得分:2)

您可以使用部分模拟来完成。这是一个靠近您的代码的示例。

首先是测试类。您需要创建一个部分模拟它。应该嘲笑getSize,但myMethod应该是测试方法。

此外,通常,您需要调用构造函数来正确初始化类(经典模拟不会调用任何构造函数)。

class MyClass {

  private boolean b1;
  private boolean b2;

  public MyClass(boolean b1, boolean b2) {
    this.b1 = b1;
    this.b2 = b2;
  }

  int myMethod() {
    return getSize();
  }

  int getSize() {
    return 42;
  }

  public boolean getB1() {
    return b1;
  }

  public boolean getB2() {
    return b2;
  }
}

测试将是以下

import org.junit.Test;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

public class MyClassTest {

  @Test
  public void test() {
    // Create a partial mock by calling its constructor
    // and only mocking getSize
    MyClass mock = createMockBuilder(MyClass.class)
        .withConstructor(true, true)
        .addMockedMethod("getSize")
        .createMock();

    // Record that getSize should return 8 (instead of 42)
    expect(mock.getSize()).andReturn(8);

    // All recording done. So put the mock in replay mode
    replay(mock);

    // Then, these assertions are to prove that the partial mock is 
    // actually doing what we expect. This is just to prove my point. Your
    // actual code will verify that myMethod is doing was is expected

    // 1. Verify that the constructor was correctly called
    assertEquals(true, mock.getB1());
    assertEquals(true, mock.getB2());
    // 2. Verify that getSize was indeed mocked 
    assertEquals(8, mock.myMethod());

    // Check everything expected was indeed called
    verify(mock);
  }
}

完成工作。请注意,这不一定是糟糕设计的标志。我经常在测试Template method pattern时使用它。

答案 1 :(得分:0)

相同类上测试另一种方法时,不应该模拟一个方法。理论上你可以这样做(使用Mokito spy 例如)。

从这个意义上说,你在错误的层面上接近这个:你实际上不应该关心你的测试方法在你测试的类中调用的其他方法。但是,如果您必须调整测试内容,那么可以采用的方法是(例如)一种方法,允许您的测试代码在调用mymethod()之前设置 size 字段。

或者:你将问题分开,然后移动"尺寸"部分到它自己的类X.然后你的测试类可以拥有一个X的实例;然后可以嘲笑那个实例。

长话短说:你想退后一步,阅读一些关于如何使用EasyMock的教程。这不是你可以通过反复试验来学习的东西。