【问题标题】:junit how would I assert that my method returns a specific arrayjunit我如何断言我的方法返回一个特定的数组
【发布时间】:2014-12-02 12:05:00
【问题描述】:

我有一个返回数组 Sighting[] 的方法。在我的单元测试中,索引 [0] 处应该有一个元素 (element1)。

我的问题是,我如何构建我的陈述来反映这一点?我需要断言我的 getMostOfSpecies 方法返回的数组在第一个索引值处包含 element1。

我的(失败的)测试看起来像这样

@Test
public void getMostOfSpeciesTest()
{
    try {
        birdList1.remember(sighting5);
        birdList1.remember(sighting6);
        birdList1.remember(sighting7);
        birdList1.remember(sighting8);
        assertEquals(birdList1.getMostOfSpecies("SOBI"), Sighting[???what to put here???]);
    }
    catch (Exception e) {
        fail("Failed" + e.getMessage());
    }
}

【问题讨论】:

    标签: java junit bluej


    【解决方案1】:

    你试过Arrays.equals() [1] 吗?确保您也覆盖了 Sighting 类的 equals() 方法。

    assertTrue( Arrays.equals(birdList1.getMostOfSpecies("SOBI"), yourSightingArray);
    

    [1]https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

    编辑:

    如果您需要检查数组是否包含一个特定对象,您可能对 Arrays.binarySearch() [2] 或 Arrays.asList() 以及 List 的 contains() 方法感兴趣。所以你的断言语句应该看起来像

    assertTrue( Arrays.binarySearch(birdList1.getMostOfSpecies("SOBI"), theElementYouExpect) >= 0);
    

    [2]https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(java.lang.Object[],%20java.lang.Object)

    【讨论】:

    • andd,我的方法返回一个数组。我需要测试它是否包含特定元素。
    • 对不起,你的问题的标题是误导“返回一个特定的数组”......但你可以在你的情况下使用 Arrays.binarySearch,我认为这就是你要找的。我将编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2022-11-04
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多