这是我的构造函数:
Merchant(
this._firstName,
this._lastName,
this._company,
this._buildingNumber,
this._location,
this._city,
String pin,
String phone,
String email,
this._image) {
_validatePin(pin) ? _pin = pin : throw pinFormatException;
_validatePhone(phone) ? _phone = phone : throw phoneFormatException;
_validateEmail(email) ? _email = email : throw emailFormatException;
}
我想对这个构造函数进行单元测试。我想测试数据验证失败时抛出的正确异常。 我希望PIN码是一个6位数字。所以,这是我为它写的测试:
test('pin must be a 6-digit number', () {
expect(() {
new Merchant(FIRST_NAME, LAST_NAME, COMPANY, BUILDING_NUMBER, LOCATION,
CITY, 1234567/*PIN*/, WHATSAPP_NUMBER, EMAIL, IMAGE_RESOURCE);
}, throwsA(Exception));
});
我想知道如何正确使用throwsA()函数来确保抛出了带有正确异常消息的正确异常。
这是我在运行上述测试时遇到的错误:
Expected: throws ?:<Exception>
Actual: <Closure: () => dynamic>
Which: threw ?:<Exception: pin codes are 6-digit numbers>
stack package:mnshi/model/merchant.dart 33:38 new Merchant
/home/raveesh/MyCode/code/production/mnshi/test/cli_tests/merchant_tests.dart 27:21 main.<fn>.<fn>.<fn>
package:test expect
/home/raveesh/MyCode/code/production/mnshi/test/cli_tests/merchant_tests.dart 27:7 main.<fn>.<fn>
package:test expect
test/cli_tests/merchant_tests.dart 27:7 main.<fn>.<fn>
请帮助!
答案 0 :(得分:3)
关闭! throwA
实际上需要另一个Matcher
,而不是Type
。
假设你有一些扩展FormatException
的东西你可以写:
expect(() {
...
}, throwsFormatException);
如果你没有,你可以制作自己的复合匹配器:
final throwsException = throwsA(const isInstanceOf<Exception>());
...
expect(() {
...
}, throwsException);
原因是你可以编写不同的复合匹配器。例如,这里有一个检查抛出的内容.toString()
为'Bad thing occured'
的内容:
expect(() {
...
}, throwsA(predicate((e) => e.toString().contains('Bad thing'));
您可以在此处了解有关匹配器的更多信息: