How to write junit tests for interfaces?

后端 未结 6 1771
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 03:49

What is the best way to write junit tests for interfaces so they can be used for the concrete implementing classes?

e.g. You have this interface and implementing cla

6条回答
  •  离开以前
    2020-11-28 04:02

    I disagree with dlev as well, there's nothing wrong with writing your tests against interfaces instead of concrete implementations.

    You probably want to use parameterized tests. Here is what it would look like with TestNG, it's a little more contrived with JUnit (since you can't pass parameters directly to test functions):

    @DataProvider
    public Object[][] dp() {
      return new Object[][] {
        new Object[] { new MyImpl1() },
        new Object[] { new MyImpl2() },
      }
    }
    
    @Test(dataProvider = "dp")
    public void f(MyInterface itf) {
      // will be called, with a different implementation each time
    }
    

提交回复
热议问题