Saturday, December 31, 2011

Assertion Statements in Junit

        In JUnit, a test occurs when ever you assert that something should be a specific value. Each JUnit test case (method) should have at least one of the assert statements listed below, otherwise the test passes, which can be misleading if you never actually check the value of any data.
        The most common assert statement is assertEquals() which takes at least two arguments. The first argument is the expected value of some piece of data at that point in the test case. The second argument is the actual value of that data, usually obtained by a method call, at that point in the test case. The method will check for equality between the two pieces of data.  For a custom object this means that the equals() and hashCode() methods should be overridden. Otherwise, the assertEquals() method will check for equality of the objects location in memory. These will be different because the expected object is created within the test case while the actual object is created within the application.
        If any of your assert statement fail, the test progress bar in the JUnit view will be red. Additionally, a failing assert statement will cease execution for that test case. Therefore, assert statements after that point will not be executed.
        This is a list of the different types of assertion statements that are used to test your code. Any Java data type or object can be used in the statement. These assertions are taken from the JUnit API.
  1. assertEquals(expected, actual)
  2. assertEquals(message, expected, actual)
  3. assertEquals(expected, actual, delta) - used on doubles or floats, where delta is the difference in precision
  4. assertEquals(message, expected, actual, delta) - used on doubles or floats, where delta is the difference in precision
  5. assertFalse(condition)
  6. assertFalse(message, condition)
  7. assertNotNull(object)
  8. assertNotNull(message, object)
  9. assertNotSame(expected, actual)
  10. assertNotSame(message, expected, actual)
  11. assertNull(object)
  12. assertNull(message, object)
  13. assertSame(expected, actual)
  14. assertSame(message, expected, actual)
  15. assertTrue(condition)
  16. assertTrue(message, condition)
  17. fail()
  18. fail(message)
  19. failNotEquals(message, expected, actual)
  20. failNotSame(message, expected, actual)
  21. failSame(message)


No comments:

Post a Comment