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

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);
}
主站蜘蛛池模板: 大石桥市| 花垣县| 醴陵市| 兴隆县| 永寿县| 钟祥市| 七台河市| 扎兰屯市| 卓尼县| 谷城县| 射阳县| 昌都县| 开化县| 神木县| 绩溪县| 隆德县| 新野县| 松阳县| 盖州市| 达州市| 西峡县| 都兰县| 棋牌| 海门市| 德州市| 华蓥市| 湟源县| 巢湖市| 乡宁县| 闵行区| 布拖县| 贞丰县| 弥勒县| 大方县| 墨竹工卡县| 霍林郭勒市| 丹东市| 家居| 红原县| 凤冈县| 玛纳斯县|