官术网_书友最值得收藏!

Assertions in depth

Assertions are methods that check for a condition that can be evaluated. If the condition is not met, the assertion method will throw an exception, thereby aborting the execution of the test.

The JUnit API includes the class Assert. This is the base class of all the TestCase classes that hold several assertion methods useful for writing tests. These inherited methods test for a variety of conditions and are overloaded to support different parameter types. They can be grouped together in the following different sets, depending on the condition checked, for example:

  • assertEquals
  • assertTrue
  • assertFalse
  • assertNull
  • assertNotNull
  • assertSame
  • assertNotSame
  • fail

The condition tested is pretty obvious and is easily identifiable by the method name. Perhaps the ones that deserve some attention are assertEquals() and assertSame(). The former, when used on objects, asserts that both objects passed as parameters are equally calling the objects' equals() method. The latter asserts that both objects refer to the same object. If, in some case, equals() is not implemented by the class, then assertEquals() and assertSame() will do the same thing.

When one of these assertions fails inside a test, an AssertionFailedException is thrown, and this indicates that the test has failed.

Occasionally, during the development process, you might need to create a test that you are not implementing at that precise time. However, you want to flag that the creation of the test was postponed (we did this in Chapter 1, Getting Started with Testing, when we added just the test method stubs). In such cases, you can use the fail() method, which always fails and uses a custom message that indicates the condition:

  public void testNotImplementedYet() {
    fail("Not implemented yet");
  }

Still, there is another common use for fail() that is worth mentioning. If we need to test whether a method throws an exception, we can surround the code with a try-catch block and force a fail if the exception was not thrown. For example:

public void testShouldThrowException() {
    try {
      MyFirstProjectActivity.methodThatShouldThrowException();
      fail("Exception was not thrown");
    } catch ( Exception ex ) {
      // do nothing
    }
  }

Note

JUnit4 has the annotation @Test(expected=Exception.class), and this supersedes the need for using fail() when testing exceptions. With this annotation, the test will only pass if the expected exception is thrown.

Custom messages

It is worth knowing that all assert methods provide an overloaded version including a custom String message. Should the assertion fail, this custom message will be printed by the test runner, instead of a default message.

The premise behind this is that, sometimes, the generic error message does not reveal enough details, and it is not obvious how the test failed. This custom message can be extremely useful to easily identify the failure once you are looking at the test report, so it's highly recommended as a best practice to use this version.

The following is an example of a simple test that uses this recommendation:

public void testMax() {
int a = 10;
int b = 20;

int actual = Math.max(a, b);

String failMsg = "Expected: " + b + " but was: " + actual;
assertEquals(failMsg, b, actual);
}

In the preceding example, we can see another practice that would help you organize and understand your tests easily. This is the use of explicit names for variables that hold the actual values.

Note

There are other libraries available that have better default error messages and also a more fluid interface for testing. One of these that is worth looking at is Fest (https://code.google.com/p/fest/).

Static imports

Though basic assertion methods are inherited from the Assert base class, some other assertions need specific imports. To improve the readability of your tests, there is a pattern to statically import the assert methods from the corresponding classes. Using this pattern instead of having:

  public void testAlignment() {
 int margin = 0;
   ...
 android.test.ViewAsserts.assertRightAligned(errorMsg, editText, margin);
  }

We can simplify it by adding the static import:

import static android.test.ViewAsserts.assertRightAligned;

public void testAlignment() {
   int margin = 0;
 assertRightAligned(errorMsg, editText, margin);
}
主站蜘蛛池模板: 郑州市| 广饶县| 芜湖市| 前郭尔| 前郭尔| 石柱| 新巴尔虎右旗| 林甸县| 东台市| 乌兰浩特市| 吴桥县| 巴彦县| 石狮市| 赣榆县| 香港| 邵东县| 化州市| 乌兰县| 诏安县| 乐至县| 锡林浩特市| 锦屏县| 阿拉善盟| 西充县| 奎屯市| 新蔡县| 盐津县| 松原市| 龙州县| 安宁市| 白银市| 图们市| 仁布县| 苗栗县| 昌图县| 乌拉特中旗| 隆安县| 彭山县| 云安县| 高州市| 沈丘县|