Search code examples
javamethodsjunitstringbuffer

JUnit to test for StringBuffers


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?


Solution

  • 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.
    }