【问题标题】:JUnit Test method that use other methods in the same object在同一对象中使用其他方法的 JUnit 测试方法
【发布时间】:2012-02-23 07:52:44
【问题描述】:

您好,我正在努力解决简单的问题。

总体思路:

class Foo(){
  public boolean method1();
  public String method2();
  public String method3();
  public String shortcut(){
    return (method1() == true) ? method2() : method3();
  }
}

我应该如何测试快捷方式?

我知道如何模拟对象和测试使用其他对象的方法。示例:

class Car{
  public boolean start(){};
  public boolean stop(){};
  public boolean drive(int km){};
}
class CarAutoPilot(){
  public boolean hasGotExternalDevicesAttached(){
     //Hardware specific func and api calls
     //check if gps is available 
     //check if speaker is on
     //check if display is on 
  }
  public boolean drive(Car car, int km){
    //drive
    boolean found = hasGotExternalDevicesAttached();
    boolean start = c.start();
    boolean drive = c.drive(km);
    boolean stop = c.stop();
    return (found && start && drive && stop) == true;   
  }
}

class CarAutoPilotTest(){
   @Test
   public void shouldDriveTenKm(){
     Car carMock = EasyMock.Create(Car.class);
     EasyMock.expect(carMock.start()).andReturns(true);
     EasyMock.expect(carMock.drive()).andReturns(true);
     EasyMock.expect(carMock.stop()).andReturns(true);
     EasyMock.reply(carMock);     

     CarAutoPilot cap = new CarAutoPilot();
     boolean result = cap.drive(cap,10);
     Assert.assertTrue(result);
     EasyMock.verify(carMock);
   }
}

但是 hasGotExternalDevicesAttached() 方法呢?这只是示例而非真实场景。我应该如何测试驱动方法?我还应该模拟 hasGotExternalDevicesAttached 函数吗?

我可以模拟正在测试的课程吗?

【问题讨论】:

  • +1 表示“我应该如何测试驾驶方法?”有趣的东西。

标签: java testing junit mocking tdd


【解决方案1】:

我会为每种方法创建一个测试。如果您降低复杂性,那么测试起来会容易得多。

这些应该有一个测试:

  public boolean method1();
  public String method2();
  public String method3();

没有必要测试最后一个方法,因为它会调用您的其他方法,但是,如果该方法发生更改(因为我猜它只是一个示例代码)并且它具有更多逻辑,那么您应该有一个测试方法也是如此。

当涉及到 hasGotExternalDevicesAttached() 时,您应该为您无法测试的所有外部 io 调用创建一个模拟程序。

如果您想提高测试技能,我建议您阅读The Art of Unit Testing。在我看来,这是初学者学习和研究单元测试艺术的最佳书籍。

【讨论】:

  • 我一直在尝试模拟外部调用,但在可能的情况下,我有简单的公共方法来检查几个布尔变量并返回状态。此方法用于同一对象中的其他公共方法。像上面的帖子那样覆盖这个方法对我来说就足够了。但我也同意你的回答。谢谢推荐书。这也很有帮助。
【解决方案2】:

您可以创建CarAutoPilot 的子类,在其中覆盖hasGotExternalDevicesAttached(),并使用此子类的实例运行测试。

你可以内联:

CarAutoPilot cap = new CarAutoPilot() {
    public boolean hasGotExternalDevicesAttached(){
        // return true or false depending on what you want to test
    }
};

这样您就可以为CarAutoPilot 的其余行为创建有效的单元测试。

如果你愿意,你可以称之为穷人的部分模仿:-)

【讨论】:

    【解决方案3】:

    是的,您可以使用 EasyMock Class Extension 库。在documentation of EasyMock 中查找“部分模拟”。

    这个想法是只模拟一个对象的一个​​(或一些)方法,并测试依赖于模拟方法的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多