2015-10-19 91 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 
} 
相關問題