JUnit to test for StringBuffers

北城以北 提交于 2020-01-06 19:31:09

问题


Assignment: Write a JUnit test assuming you have two StringBuffer references named sbOne and sbTwo and you only want it to pass if the two references point to the same StringBuffer object.

I want to make sure this actually a good way to approach this assignment. I wrote the assumed method for practice:

package StringBufferJUni;

public class StringBufferUni {

    public static void main(String[] args){

    }

    public boolean StringBuff(StringBuffer sbOne, StringBuffer sbTwo){
        sbTwo = sbOne;
        if(sbTwo==sbOne){
            return true;
        }

        else{
            return false;
        }
    }
}

And this is my JUnit test:

package StringBufferJUni;

import static org.junit.Assert.*;

import org.junit.Test;

public class JUnitStringBuffer {

    @Test
    public void test() {
        StringBuffer sbOne = new StringBuffer("hello");
        StringBuffer sbTwo = new StringBuffer("hello");
        StringBufferUni stBuffer = new StringBufferUni();
        boolean hel = stBuffer.StringBuff(sbOne, sbTwo);
        assertEquals(true, hel);
    }

}

Is this actually passing due to the references pointing to the same object?


回答1:


This line:

sbTwo = sbOne;

is setting one object reference to the value of another.

This line:

if( sbTwo==sbOne )

is comparing to see if the two references are equal, which will always be true because of the above line.

It's not comparing anything about the object itself (ie: it's not the same as sbOne.equals(sbTwo))

If you want to tell if the references point to the same object, then you need to simply use:

if (sbTwo==sbOne)

and remove the line: sbTwo=sbOne

For further consideration, this test illustrates what you are doing:

@Test
public void test() {
    StringBuffer sb1 = new StringBuffer("hello");
    StringBuffer sb2 = sb1;

    assertTrue(sb1 == sb2);  // this will pass, same object reference

    sb2 = new StringBuffer("hello");  // create a new object

    assertFalse(sb1 == sb2);  // this will be false, since the objects may be equal, but the references are not.
}


来源:https://stackoverflow.com/questions/30494332/junit-to-test-for-stringbuffers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!