onstructor SortString [] [],11,12; \\“在junit中未定义

问题描述

| 我正在尝试为以下方法编写测试:
 public class Sort {

...
...
...

    public static String[][] findRanks(String[][] array,int indexOfPoints,int indexOfRank) {

        for (int i = 0; i < array.length - 1; i++) { 
            int compare = 1;
            if (i < array.length - 2)
                compare = Double.valueOf(array[i][indexOfPoints]).compareto(Double.valueOf(array[i + 1][indexOfPoints]));

            if (i == array.length - 1 || compare != 0) { 
                array[i][indexOfRank] = Integer.toString(i + 1);
            }
            else {
                array[i][indexOfRank] = Integer.toString(i + 1) + \" - \" + Integer.toString(i + 2);
                array[i+1][indexOfRank] = Integer.toString(i + 1) + \" - \" + Integer.toString(i + 2);
                i++;
            }
        }
        return array;   
    }

}
我已经尝试了以下测试:
import static org.junit.Assert.*;
import junit.framework.TestCase;
import org.junit.Test;

public class SortTest extends TestCase {

    @Test
    public void testFindRanks() {
        String[][] array = { {\"Siim Susi\",\"12.61\",\"5.00\",\"9.22\",\"1.50\",\"60.39\",\"16.43\",\"21.60\",\"2.60\",\"35.81\",\"5.25.72\",\"6253.0\",\"1\"},{\"Beata Kana\",\"13.04\",\"4.53\",\"7.79\",\"1.55\",\"64.72\",\"18.74\",\"24.20\",\"2.40\",\"28.20\",\"6.50.76\",\"5290.0\",\"2\"}};

        Sort test1 = new Sort(array,11,12); //This is where the problem is

        String[][] expected = { {\"Siim Susi\",\"2\"}};

        assertTrue(expected.equals(test1));
        fail(\"Not yet implemented\");
    }

}
但是测试不断告诉我“构造函数Sort(String [] [],11,12); \”是未定义的。 为什么认为它必须是构造函数,我该如何解决? 谢谢。     

解决方法

你应该写
    String[][] results = Sort.findRanks(array,11,12);
为了使单元测试更整洁,更惯用且更易于维护,您还可以对其进行一些重构:
public class SortTest extends TestCase {

    @Test
    public void testFindRanks() {
        String[][] array = {...};
        String[][] expected = {...};

        String[][] result = Sort.findRanks(array,12);

        assertArrayEquals(expected,result);
    }
}
也就是说,将测试设置,对被测试方法的调用以及验证代码分开。还要从头删除“ 4”调用,因为这会使您的测试始终失败:-)     ,看起来你需要做
 String[][] actual = Sort.findRanks(array,12);
接着
assertArrayEquals(expected,actual);
    ,这是一个构造函数调用:
new Sort(array,12)
而且编译器会抱怨没有这样的构造函数 在Java教程中了解有关构造函数的信息     ,消息完全正确:您的
Sort
类未定义将
String[][],int,int
作为参数的构造函数,您正在有问题的行上调用该构造函数。 你需要:
String[][] actual = Sort.findRanks(array,12);
    ,好吧,看起来您没有定义
Sort
构造函数(至少在您发布的代码中)。而且编译器/ IDE告诉您没有定义
Sort
构造函数。 您可能是想拨打此行:
String[][] value = Sort.findRanks(array,12);
//Sort test1 = new Sort(array,12); <-- dont call this...call the above...