简体   繁体   English

如何使用EasyMock从父类模拟方法

[英]How to mock the method from parent class with EasyMock

public abstract class A{
    public int methodInA(String a){
         return 0;
    }
}

public class B extends A{
    String a = "ANYTHING";
    public void main(){
        int b = super.methodInA(a);
    }
}

This code is just an example. 这段代码只是一个例子。 I am trying to test B and want to mock the method methodINA with arguments from B . 我正在尝试测试B并想使用B参数模拟方法methodINA Can I do this with EasyMock and if so how? 我可以用EasyMock做到这一点吗?

This is not what mocking is for, you should be mocking the method main but that makes the test pointless as you won't test the actual code just EasyMock. 这不是模拟的目的,您应该模拟main方法,但这会使测试毫无意义,因为您将不会仅测试EasyMock的实际代码。

EasyMock (and mocking in general) is used when you want to control the behaviour of an object used by an object under test. 当您想控制被测对象使用的对象的行为时,将使用EasyMock(通常是模拟)。

In your case the only option you have is to subclass B in your test, like this for example: 在您的情况下,唯一的选择是在测试中将B子类化,例如:

@Test
public void testSomething()
{
  final int expected = 5;

  B b = new B()
  {
    public int methodInA(String a)
    {
      return expected;
    }
  };

  b.main();

  //Add assertions here.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM