简体   繁体   English

JUnit4(assertEquals)说对象不同,当它们相同时?

[英]JUnit4 (assertEquals) saying objects are different, when they're the same?

I'm testing my code using JUnit4 to see if an insertion sort of an array of objects ( Word(String a, int b) ) is correctly sorting the array.我正在使用 JUnit4 测试我的代码,以查看对象数组( Word(String a, int b) )的插入排序是否正确地对数组进行排序。 The problem I'm having is that when I run JUnit it fails, giving me an error: "expected {One, 1} but was {One, 1}."我遇到的问题是,当我运行 JUnit 时,它失败了,给我一个错误:“预期为 {One, 1} 但为 {One, 1}。” If I print out both values I'm comparing before I run the test they are also the same.如果我在运行测试之前打印出我正在比较的两个值,它们也是相同的。 The code is:代码是:

package sort;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class InsertionTest {
    private Word word1;
    private Word word2;
    private Word word3;
    private Word word4;
    private Word wordExpected1;
    private Word wordExpected2;
    private Word wordExpected3;
    private Word wordExpected4; 

    @Before
    public void setUp() throws Exception {
        word1 = new Word("One", 1);
        word2 = new Word("Two", 2);
        word3 = new Word("Three", 3);
        word4 = new Word("Four", 4);
        wordExpected1 = new Word("One", 1);
        wordExpected2 = new Word("Two", 2);
        wordExpected3 = new Word("Three", 3);
        wordExpected4 = new Word("Four", 4);
    }

    @After
    public void tearDown() throws Exception {
    }

    @SuppressWarnings("deprecation")
    @Test
    public void test() {
        Word[] wordList = { word3, word2, word4, word1 };
        Word[] expected = { wordExpected1, wordExpected2, wordExpected3, wordExpected4 };
        Insertion.sortInsert(wordList);
        assertEquals(expected, wordList);
    }
}

The code for the insertionsort:插入排序的代码:

package sort;
public class Insertion {
/**
 * regular insertion sort
 * @param x - the input array containing scores of words that need to be sorted.
 */
    public static void sortInsert ( Word[] x) {
        int N = x.length;

        for (int i = 1; i < N; i++){
            int tempScore = x[i].getScore();
            String tempWord = x[i].getWord();
            int j;

            for (j = (i - 1); j >= 0 && tempScore < x[j].getScore(); j--){
                x[j + 1].setScore(x[j].getScore());
                x[j + 1].setWord(x[j].getWord());
            }

            x[j + 1].setScore(tempScore);
            x[j + 1].setWord(tempWord);
        }
    }
}

The code for the ADT: ADT的代码:

package sort; 
public class Word implements Comparable<Word>{
    private String word;
    private int score;

    public Word(String w, int s){
        this.word = w;
        this.score = s;
    }

    public int getScore(){
        return score;
    }

    public void setScore(int s){
        score = s;
    }

    public String getWord(){
        return word;
    }

    public void setWord(String w){
        word = w;
    }

    @Override
    public int compareTo(Word w){
        if ((this.score) > (w.score)) { return 1; }
        else if ((this.score) < (w.score)) { return -1; }
        return 0;
    }

    public String toString(){
        return ("{" + this.word + "," + this.score + "}");
    }
}

Any help would be appreciated, thank you!任何帮助将不胜感激,谢谢!

You're creating two different objects.您正在创建两个不同的对象。 Just because their attributes have the same value, they are not necessarily equal.仅仅因为它们的属性具有相同的值,它们并不一定相等。 To achive this, you need to override the equals() method in class Word .要实现这一点,您需要覆盖Word类中的equals()方法。

Thus, add:因此,添加:

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Word other = (Word) obj;
        if (score != other.score)
            return false;
        if (word == null) {
            if (other.word != null)
                return false;
        } else if (!word.equals(other.word))
            return false;
        return true;
    }

Eclipse provides an easy way to do this (semi-)automatically. Eclipse 提供了一种简单的方法来(半)自动执行此操作。 Open your Word class, select Source -> Generate hashCode() and equals()... Select attributes that should be considered when checking two Word objects for equality.打开您的Word类,选择Source -> Generate hashCode() 和 equals()...选择在检查两个Word对象是否相等时应考虑的属性。

Also, you should oderride hashCode() .此外,您应该使用hashCode() Related questions:相关问题:

By the way: Might be a copy&paste issue, but implemented methods from interfaces are not being annotated with @Override (as your compareTo() is).顺便说一句:可能是复制和粘贴问题,但接口中实现的方法没有用@Override注释(就像你的compareTo() )。 @Override annotation would be appropriate for toString() since you override the toSting() -method of class Object . @Override注释适用于toString()因为您覆盖了类ObjecttoSting()方法。

From @Override Javadoc:来自@Override Javadoc:

Indicates that a method declaration is intended to override a method declaration in a supertype.指示方法声明旨在覆盖超类型中的方法声明。

JUnit's assertEquals depends on you correctly implementing Object.equals(Object) , which you didn't do. JUnit 的assertEquals取决于您正确实现Object.equals(Object) ,而您没有这样做。 Implement equals(Object) in Word to make this work.Word实现equals(Object)来完成这项工作。

Use Lombok to generate the equal and hashcode method.使用 Lombok 生成 equal 和 hashcode 方法。 Then it will work.然后它会起作用。 Your code will also become clean by using Lombok annotations.通过使用 Lombok 注释,您的代码也将变得干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM