2015-10-19 90 views
1

假设我有三个类A,B,C。 所有三者都做同样的事情,但以不同的方式,它们的效率不同。 三个类中的所有方法名称,变量名都是相同的。将不同类的对象作为参数传递给相同的方法

class A{ 
    public static int method(){ 
    ...... 
    return result; 
    } 
} 
class B{ 
    public static method(){ 
    ...... 
    return result; 
    } 
} 
class C{ 
    public static method(){ 
    ...... 
    return result; 
    } 
} 

我有测试类,它有一个方法来测试上述三个类中的代码。由于这个testMethod()对所有三个类都很常见,有没有办法用classes A,B,C的对象调用这个方法?

class Test{ 
    public static int testMethod(Object ABC) 
    { 
     return ABC.method(); 
    } 

    public static void main(String[] args){ 
     A a = new A(); 
     SOP(testMethod(a)); 
     B b = new B(); 
     SOP(testMethod(b)); 
     C c = new C(); 
     SOP(testMethod(c)); 
    } 
} 

我能想到的唯一方法是为每个类创建三种不同的方法,就像这样。

class Test{ 
    public static int testMethodA(A a) 
    { 
     return a.method(); 
    } 

    public static int testMethodB(B b) 
    { 
     return b.method(); 
    } 

    public static int testMethodC(C c) 
    { 
     return c.method(); 
    } 

    public main() 
    { 
     //call to each of the three methods 
     ............ 
    } 

此场景的最佳方法是什么?基本上我想只有一种方法可以测试所有三个类。

回答

3

用所有类的通用方法创建一个接口。然后,让每个类实现这个接口。在您的测试代码中,使用接口作为参数类型并将每个类的实例传递给方法。请注意,当你这样做时,测试的方法不应该是静态的。

在代码:

public interface MyInterface { 
    //automatically public 
    int method(); 
} 

public class A implements MyInterface { 
    @Override //important 
    //not static 
    public int method() { 
     /* your implementation goes here*/ 
     return ...; 
    } 
} 

public class B implements MyInterface { 
    @Override //important to check method override at compile time 
    public int method() { 
     /* your implementation goes here*/ 
     return ...; 
    } 
} 

//define any other class... 

然后测试:

public class Test { 
    //using plain naive console app 
    public static void main(String[] args) { 
     MyInterface myInterfaceA = new A(); 
     testMethod(myInterfaceA); 
     MyInterface myInterfaceB = new B(); 
     testMethod(myInterfaceB); 
     //and more... 
    } 

    public static void testMethod(MyInterface myInterface) { 
     myInterface.method(); 
    } 
} 

或者,如果你喜欢使用JUnit:

import static org.hamcrest.Matchers.*; 
import static org.junit.Assert.*; 

public class MyInterfaceTest { 
    MyInterface myInterface; 

    @Test 
    public void methodUsingAImplementation() { 
     myInterface = new A(); 
     //code more human-readable and easier to check where the code fails 
     assertThat(myInterface.method(), equalTo(<expectedValue>)); 
    } 
    //similar test cases for other implementations 
} 
相关问题