JUnit测试StringBuffers [英] JUnit to test for StringBuffers

查看:195
本文介绍了JUnit测试StringBuffers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分配:编写一个JUnit测试,假设您有两个名为sbOne和sbTwo的StringBuffer引用,并且仅当两个引用指向同一个StringBuffer对象时才希望它通过.

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;
        }
    }
}

这是我的JUnit测试:

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?

推荐答案

此行:

sbTwo = sbOne;

将一个对象 reference 设置为另一个对象的值.

is setting one object reference to the value of another.

此行:

if( sbTwo==sbOne )

进行比较以查看两个引用是否相等,因为上面的行,这将始终为真.

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

它没有对对象本身进行任何比较(即:它与sbOne.equals(sbTwo)相同不相同)

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)

并删除以下行: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.
}

这篇关于JUnit测试StringBuffers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆