【问题标题】:EasyMock condition and logicEasyMock 条件和逻辑
【发布时间】:2011-05-03 04:40:32
【问题描述】:

有没有办法让 EasyMock 使用条件?我的方法中有一个 if-else 块,但只有在我删除条件块时测试才会通过。这可能是 JUnit 而不是 EasyMock 的问题。有人知道这方面的信息吗?

【问题讨论】:

  • 请提供代码示例,没有它你的问题很难理解

标签: unit-testing testing junit easymock


【解决方案1】:

如果我正确理解您的问题,您希望根据变量返回不同的值。 最好的方法是使用 IAnswer 界面。

假设您有一个 DAO 类从一个点获取颜色:

public class ColorDAO {
   public Color getColorFromPoint(Point point) {
       //Implementation
   }
} 

您可以为此创建一个答案:

ColorDao colorDao = EasyMock.createMock(ColorDao.class);
EasyMock.expect(colorDao.getColorFromPoint(EasyMock.anyObject(Point.class))).andAnswer(new IAnswer<Color>() {    
         @Override
         public Color answer() throws Throwable {
            Point point = (Point) EasyMock.getCurrentArguments()[0];
            if (point .getX() > 0.0) {
               return Color.BLACK;
            }
            return Color.YELLOW;
         }
      });
EasyMock.replay(colorDao);

希望有所帮助;)

【讨论】:

    【解决方案2】:

    是测试中的条件还是被测试的方法?

    如果它在测试中,您可以有一个助手来根据输入设置您的期望,或者您可以对各种输入有期望。这些都不取决于被测试方法的行为。

    如果它在被测试的方法中,那么你设置期望的方式不受被测试的方法的影响,你需要像正常一样为你的模拟行为设置期望。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2011-07-26
      • 2015-02-27
      • 2012-10-25
      相关资源
      最近更新 更多