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

查看:19
本文介绍了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?

推荐答案

当比较 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) 绝对是安全的.(因为Strings 是Objects)

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天全站免登陆