9

assertEquals を使用して、例外メッセージが正しいかどうかを確認するにはどうすればよいですか? テストはパスしますが、正しいエラーにヒットするかどうかはわかりません。

私が実行しているテスト。

@Test
public void testTC3()
{
    try {
    assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
    } 
    catch (Exception e) {
    }        
}

テスト中のメソッド。

public static int shippingCost(char packageType, int weight) throws Exception
{
    String e1 = "Legal Values: Package Type must be P or R";
    String e2 = "Legal Values: Weight < 0";
    int cost = 0;
        if((packageType != 'P')&&(packageType != 'R'))
        {
             throw new Exception(e1);
        }

        if(weight < 0)
        {
             throw new Exception(e2);
        }        
         if(packageType == 'P')
         {
             cost += 10;
         }
         if(weight <= 25)
         {   
             cost += 10;
         }
         else
         {
            cost += 25;
         }
         return cost;       
}

}

助けてくれてありがとう。

4

5 に答える 5

11
try {
    assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
    Assert.fail( "Should have thrown an exception" );
} 
catch (Exception e) {
    String expectedMessage = "this is the message I expect to get";
    Assert.assertEquals( "Exception message must be correct", expectedMessage, e.getMessage() );
}   
于 2012-04-13T20:49:19.693 に答える
5

あなたの例の assertEquals は、メソッド呼び出しの戻り値を期待値と比較していますが、これはあなたが望むものではありません。もちろん、期待される例外が発生した場合、戻り値はありません。assertEquals を catch ブロックに移動します。

@Test
public void testTC3()
{
    try {
        Shipping.shippingCost('P', -5);
        fail(); // if we got here, no exception was thrown, which is bad
    } 
    catch (Exception e) {
        final String expected = "Legal Values: Package Type must be P or R";
        assertEquals( expected, e.getMessage());
    }        
}
于 2012-04-13T20:49:58.053 に答える
2

私にとって完璧に機能します。

try{
    assertEquals("text", driver.findElement(By.cssSelector("html element")).getText());
    }catch(ComparisonFailure e){
        System.err.println("assertequals fail");
    }

assertEquals が失敗した場合、ComparisonFailure が処理します

于 2016-03-31T09:56:42.797 に答える
0

これは、クリーンな方法で例外をアサートできる優れたライブラリです。

例:

// given: an empty list
List myList = new ArrayList();

// when: we try to get the first element of the list
when(myList).get(1);

// then: we expect an IndexOutOfBoundsException
then(caughtException())
        .isInstanceOf(IndexOutOfBoundsException.class)
        .hasMessage("Index: 1, Size: 0")
        .hasNoCause();
于 2016-05-31T16:51:29.373 に答える