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

  • Dart Cookbook
  • Ivo Balbaert
  • 377字
  • 2021-08-05 17:42:47

Microtesting your code with assert

Writing tests for your app is necessary, but it is not productive to spend much time on trivial tests. An often underestimated Dart keyword is assert, which can be used to test conditions in your code.

How to do it...

Look at the code file microtest.dart, where microtest is an internal package as seen in the previous recipe:

import 'package:microtest/microtest.dart';

void main() {
 Person p1 = new Person("Jim Greenfield", 178, 86.0);
 print('${p1.name} weighs ${p1.weight}' );
 // lots of other code and method calls
 // p1 = null;
 // working again with p1:
 assert(p1 is Person); 
 p1.weight = 100.0;
 print('${p1.name} now weighs ${p1.weight}' );
} 

We import the microtest library, which contains the definition of the Person class. In main(), we create a Person object p1, go through lots of code, and then want to work with p1 again, possibly in a different method of another class. How do we know that p1 still references a Person object? In the previous snippet, it is obvious, but it can be more difficult. If p1 was, for example, dereferenced, without assert we would get the exception NoSuchMethodError: method not found: 'weight='.

However, if we use the assert statement, we get a much clearer message: AssertionError: Failed assertion: line 9 pos 9: 'p1 is Person' is not true. You can test it by uncommenting the line p1 = null.

How it works...

The assert parameter is a logical condition or any expression (such as calling a function returning a Boolean value) that resolves to false or true. If its value is false, the normal execution is stopped by throwing an AssertionError.

Use assert to test any non-obvious conditions in your code; it can replace a lot of simple unit tests or unit tests that can be difficult to set up. Rest assured assert only works in the checked mode; it does not affect the performance of your deployed app because it is ignored in the production mode.

There's more...

Testing with assert is often very useful when entering a method to test conditions on parameters (preconditions), and on leaving a method testing the return value (postconditions). You can also call a test function (which has to return a Boolean value) from assert such as assert(testfun ction());.

主站蜘蛛池模板: 南城县| 江华| 龙井市| 益阳市| 赞皇县| 湘潭县| 竹北市| 林口县| 昭觉县| 教育| 福贡县| 农安县| 灌阳县| 正宁县| 松江区| 得荣县| 望奎县| 溆浦县| 墨玉县| 城固县| 三河市| 邹城市| 广东省| 辽宁省| 田阳县| 祁门县| 望城县| 昆明市| 汤原县| 三江| 达孜县| 霍城县| 镇康县| 方正县| 略阳县| 丹寨县| 南溪县| 巧家县| 宜宾市| 庐江县| 奉节县|