【问题标题】:How to mock a function call while initializing a variable in @Tested testObject in junit如何在junit的@Tested testObject中初始化变量时模拟函数调用
【发布时间】:2017-11-14 08:31:03
【问题描述】:

我有一个类 A,它有一个私有整数成员 b。这是类的结构:

public class A {

    private int b= Integer.parseInt(C.getValue(anyString));

    public int getB() {
       return b;
    }

    public void setB(int b) {
       this.b= b;
    }

}

我正在使用 jmockit 和 junit4 测试这个类的一些方法`

public class ATest {

    @Tested
    A a;

    @BeforeClass
    public void setUp() {
       //mock C.getValue
    }

    @Test public void test1() {
       //some test code
    }
}

但我无法模拟调用 (C.getValue(anyString)),因此在构建项目时测试失败。我尝试过使用@Before 和@BeforeClass,但没有一个执行过一次。请提出出路。 考虑到我不能更改主类A。

【问题讨论】:

  • C是什么类型的类?
  • 假设它是一个为特定键执行数据库查找的类。
  • 尝试使用 NonStrictExpectation 进行部分模拟

标签: java unit-testing junit jmockit


【解决方案1】:

首先,您这样做的方式不是很好,因为您无法控制从类 C 返回的值。但是如果你想保持你的代码这样,你可以提取

C.getValue(anyString)

到你的类中的新受保护函数

public class A {

   private int b= Integer.parseInt(getValue(anyString));

   public int getB() {
      return b;
   }

   public void setB(int b) {
      this.b= b;
   }

   protected String getValue(String anyString) {
      return C.getValue(anyString);
   }
}

之后,您可以在您的测试类中创建扩展类 A 的新私有类,然后覆盖其

getValue(String anyString)

功能。

在测试类中:

public class ATest extends A {

    @Override protected String getValue(String anyString) {
      return "return 1 or any other string reperesentation of number";
   }
}

函数getValue(String anyString),我们称之为AText类,然后可以返回你选择的值。这样,您将拥有受控环境,并且可以测试这个新的 ATest 类。

【讨论】:

    【解决方案2】:

    根本原因是您的代码违反了单一职责/关注点分离原则。这也是 work in constructor 代码异味的一个例子。

    你的类A 看起来很像一个数据传输对象 (DTO),它唯一的职责就是传输数据。从数据库中获取数据应该由类外的某个框架完成,数据应该从外部传入。

    【讨论】:

    • 实际上它是struts中的一个动作类,但我完全同意你的观点。问题是我没有编写该代码,我无权更改它。我只限于测试类。无论如何感谢您的观点:)
    • @sbajpai “我无权改变它。” 那么你应该向你的经理提出这个问题。这应该作为失败的测试来处理。在最坏的情况下,您可以使用 PowerMock,但这只是最后的手段。
    【解决方案3】:

    问题解决了。只需在 @BeforeClass 中的 setUp() 方法中添加静态并模拟调用。这不是正确的方法,但我只被允许更改测试类。

    【讨论】:

    • 您仍然应该向您的经理提出这个问题。从长远来看,这种编码风格会减慢开发速度,因为它使代码高度耦合,因此不灵活,难以扩展和维护。
    猜你喜欢
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多