【问题标题】:Is it possible to Mock the Platform APIs in eclipse to do Junit test?是否可以在 Eclipse 中模拟平台 API 来进行 Junit 测试?
【发布时间】:2021-06-29 03:55:40
【问题描述】:

我正在开发 Eclipse 插件,我需要对其进行一些测试。 我想在我的测试类中监视 Eclipse 运行时平台 API。 我的例子中提到的场景很容易理解。

Class MyClass{
private boolean foo(){
  if (Platform.inDebugMode())
    {
    return  false;
    }
    else{
     return true;
   }
 }
}

Now I need to test  foo() method completly
 class MyClassTest{
MyClass myClass = new MyClass();

@Test
public void testFoo(){
assertTrue(myClass.foo()); 
}

@Test
public void testFooWithDebugMode(){
Mockito.doReturn(true).when(Platform).inDebugMode(); // Is this possible to mock this?
assertFalse(myClass.foo()); ​
}
}

【问题讨论】:

  • 实际问题是什么?你知道Mockito::mockStatic吗?
  • 不多,但我的问题是我需要在不使用powermockito的情况下模拟静态方法
  • 你看过上面的评论了吗?来看看mockStatic 怎么样?

标签: java eclipse junit mockito platform


【解决方案1】:

是的,可以将平台 API 模拟到 Eclipse 中进行 Junit 测试 但在此之前,用户必须安装以下插件。

  1. org.eclipse.core.runtime
  2. org.eclipse.ui
  3. org.eclipse.ui.forms

【讨论】:

    【解决方案2】:

    我对 eclipse 平台和 eclipse 插件开发一无所知,但是,除了处理静态,您可以考虑以下内容:

    interface MyPlatformAdapter {
       boolean isInDebugMode();
    }
    
    class MyPlatformAdapaterImpl implements MyPlatformAdapter {
       public boolean isInDebugMode() {
         return Platform.inDebugMode();
       } 
    }
    

    现在您的代码变得简单且可单元测试:

    Class MyClass{
      private final MyPlatformAdapter platform;
    
      public MyClass(MyPlatformAdapter platform) {
        this.platform = platform;
      }
      public boolean foo() {
         if (platform.isInDebugMode())
        {
        return  false;
        }
        else{
         return true;
       }
     }
    }
    

    而且测试很简单 - 不需要像 PowerMockito 这样您试图避免的工具或 mockito 的静态方法模拟工具。

    假设您使用这个“平台”,它充满了来自许多类的此类静态方法,这种方法可以简化测试,并且通常可以使您的代码更好。我有点同意,在您的项目中使用 Platform 的地方越少,这看起来就越过分,但 IMO 仍然是一种可行的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 2012-05-14
      • 1970-01-01
      相关资源
      最近更新 更多