Why doesn't JUnit provide assertNotEquals methods?

后端 未结 11 1077
忘了有多久
忘了有多久 2020-12-12 08:30

Does anybody know why JUnit 4 provides assertEquals(foo,bar) but not assertNotEqual(foo,bar) methods?

It provides assertNotSame

相关标签:
11条回答
  • 2020-12-12 09:16

    I'm coming to this party pretty late but I have found that the form:

    static void assertTrue(java.lang.String message, boolean condition) 
    

    can be made to work for most 'not equals' cases.

    int status = doSomething() ; // expected to return 123
    assertTrue("doSomething() returned unexpected status", status != 123 ) ;
    
    0 讨论(0)
  • 2020-12-12 09:17

    I wonder same. The API of Assert is not very symmetric; for testing whether objects are the same, it provides assertSame and assertNotSame.

    Of course, it is not too long to write:

    assertFalse(foo.equals(bar));
    

    With such an assertion, the only informative part of the output is unfortunately the name of the test method, so descriptive message should be formed separately:

    String msg = "Expected <" + foo + "> to be unequal to <" + bar +">";
    assertFalse(msg, foo.equals(bar));
    

    That is of course so tedious, that it is better to roll your own assertNotEqual. Luckily in future it will maybe be part of the JUnit: JUnit issue 22

    0 讨论(0)
  • 2020-12-12 09:18

    The obvious reason that people wanted assertNotEquals() was to compare builtins without having to convert them to full blown objects first:

    Verbose example:

    ....
    assertThat(1, not(equalTo(Integer.valueOf(winningBidderId))));
    ....
    

    vs.

    assertNotEqual(1, winningBidderId);
    

    Sadly since Eclipse doesn't include JUnit 4.11 by default you must be verbose.

    Caveat I don't think the '1' needs to be wrapped in an Integer.valueOf() but since I'm newly returned from .NET don't count on my correctness.

    0 讨论(0)
  • 2020-12-12 09:18

    Usually I do this when I expect two objects to be equal:

    assertTrue(obj1.equals(obj2));
    

    and:

    assertFalse(obj1.equals(obj2));
    

    when they are expected to be unequal. I am aware that this not an answer to your question but it is the closest I can get. It could help others searching for what they can do in JUnit versions before JUnit 4.11.

    0 讨论(0)
  • 2020-12-12 09:23

    There is an assertNotEquals in JUnit 4.11: https://github.com/junit-team/junit/blob/master/doc/ReleaseNotes4.11.md#improvements-to-assert-and-assume

    import static org.junit.Assert.assertNotEquals;
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题