Java的assertEquals方法可靠吗? [英] Is Java's assertEquals method reliable?

查看:58
本文介绍了Java的assertEquals方法可靠吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道比较两个Strings==有一些问题.似乎String.equals()是更好的方法.好吧,我正在进行JUnit测试,我倾向于使用assertEquals(str1, str2).这是断言两个字符串包含相同内容的可靠方法吗?我会使用assertTrue(str1.equals(str2)),但是那样的话,您将无法获得预期的失败值和实际值.

I know that == has some issues when comparing two Strings. It seems that String.equals() is a better approach. Well, I'm doing JUnit testing and my inclination is to use assertEquals(str1, str2). Is this a reliable way to assert two Strings contain the same content? I would use assertTrue(str1.equals(str2)), but then you don't get the benefit of seeing what the expected and actual values are on failure.

在相关说明中,是否有人链接到页面或线程,这些页面或线程清楚地说明了str1 == str2的问题?

On a related note, does anyone have a link to a page or thread that plainly explains the problems with str1 == str2?

推荐答案

在Java中比较Strings时,应该始终使用.equals().

You should always use .equals() when comparing Strings in Java.

JUnit调用.equals()方法来确定方法assertEquals(Object o1, Object o2)中的相等性.

JUnit calls the .equals() method to determine equality in the method assertEquals(Object o1, Object o2).

因此,使用assertEquals(string1, string2)绝对是安全的. (因为StringObject)

So, you are definitely safe using assertEquals(string1, string2). (Because Strings are Objects)

这是一个有关Stackoverflow的重要问题的链接关于==.equals()之间的某些差异.

Here is a link to a great Stackoverflow question regarding some of the differences between == and .equals().

这篇关于Java的assertEquals方法可靠吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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