2015-06-27 55 views
0

代碼示例:我TestNG的方法裏面TestNG的類,通過反射調用其他方法失敗登錄TestNG的報告

的Test1類將是這將是負責執行的Test2類方法

一個父類

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;

import org.testng.annotations.Test;

公共類測試1 {

@Test 
public void test() { 
    Class test2 = Test2.class; 
    Method method = null; 
    Object obj = null; 
    try { 
     method = test2.getMethod("test", String.class); 
    } catch (NoSuchMethodException | SecurityException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    method.setAccessible(true); 

    try { 
     obj = method.invoke(test2.newInstance(), "0"); 

    } catch (IllegalAccessException | IllegalArgumentException 
      | InvocationTargetException | InstantiationException e) { 
     // TODO Auto-generated catch block 

     e.printStackTrace(); 
    } 

} 

}

Test2.class代碼:

進口org.testng.Assert;

公共類的Test2 {

public void test(String obj){ 

    Assert.assertEquals(obj, "1"); 
} 

} 這裏按照本例,斷言失敗,但TestNG的報告指出如通過 讓我怎麼斷言失敗鏈接到TestNG的報告

+0

你想通過從另一個班級調用測試來實現什麼?爲什麼不使用xml或testng編程式調用? –

回答

0

我認爲將單個catch塊中的InvocationTargetException處理程序隔離並使用getCause()檢查結果會更好。這是我的嘗試;

try { 
    Object obj = method.invoke(test2obj, "0"); 
} catch(InvocationTargetException e){ 
    Throwable e1 = e.getCause(); 
    System.out.println("Method invocation failed... due to " + e1); 
} catch (IllegalAccessException | IllegalArgumentException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

我收到了這條消息;

Method invocation failed... due to org.junit.ComparisonFailure: expected:<[0]> but was:<[1]>