【问题标题】:Junit: Assert.assertNotSame returning true despite the fact the two strings are equalJunit:尽管两个字符串相等,但 Assert.assertNotSame 返回 true
【发布时间】:2015-09-04 19:58:42
【问题描述】:

我正在使用 JUnit 4.12 和 PowerMock 1.6.2。我有以下代码:

import org.junit.Assert;
...
System.out.println("equals?" + obj.equals(myObj.getUser().getUserName()));
Assert.assertNotSame(obj.getUserName(), myObj.getUser().getUserName());

系统输出调用打印equals? true,但是下面的断言行成功,如果字符串相等,我希望它会失败。为什么assertNotSame 不起作用,我应该使用什么正确的方法?

【问题讨论】:

    标签: java junit assertions


    【解决方案1】:

    assertNotSame(a, b) 检查a != b,即 a 和 b 不是对完全相同对象的引用。这与测试a.equals(b) 是否为假非常不同,后者会检测两个字符串不具有相同的字符。

    你应该使用

    assertFalse(obj.getUserName().equals(myObj.getUser().getUserName()))
    

    我建议使用AssertJ,它有几十个更具表现力的断言:

    assertThat(myObj.getUser().getUserName()).isNotEqualTo(obj.getUserName());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      相关资源
      最近更新 更多