简体   繁体   English

在JUnit中使用assertEquals(Object [],Object [])?

[英]assertEquals(Object[], Object[]) in JUnit?

So I was going through the JUnit 4.0 testing and I test object (Stick) arrays if they are equal, which they are, but I get a failure test. 因此,我正在进行JUnit 4.0测试,并且测试了对象(Stick)阵列是否相等(相等),但是我进行了故障测试。

Stick class: 棒类:

 public class Stick {
        private char stick;

        public Stick() {
            stick = 'I';
    }

The Game class - where I initialize the array of Stick: Game类-在其中初始化Stick数组:

public class Game {
private Stick[] sticks;

public Stick[] StartNewGame() {
    counter = 1;
    sticks = new Stick[22];

    for(int i = 0; i<sticks.length; i++) {
        Stick a_stick = new Stick();
        sticks[i] = a_stick;
    }
    return sticks;
}

The test code: 测试代码:

@Test
    public void ShouldStartAGame() {
        Stick[] sticks = new Stick[22];
        for(int i = 0; i<sticks.length; i++) {
            Stick a_stick = new Stick();
            sticks[i] = a_stick;
        }
        assertArrayEquals(sticks, game.StartNewGame());

    }

I think, this is due to the lack of an equals method on Stick, so equals is comparing the memory address of the Stick[] elements and finding them to be different. 我认为,这是由于Stick上缺少equals方法,所以equals比较Stick[]元素的内存地址并发现它们是不同的。

Override the default equals (and hashcode ) methods in Stick. 覆盖Stick中的默认equals (和hashcode )方法。

Also the test violates the DRY principle, as you are repeating your implementing code in the test, if you duplicate a mistake from the implementation into the test using cut and paste no unit test in the world will find a mistake. 测试还会违反DRY原理,因为您在测试中重复执行代码,如果您使用剪切和粘贴将实现中的错误复制到测试中,那么世界上没有任何单元测试会发现错误。

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

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