When trying to assign a value of a wrong type to a variable in Dart, you get a _TypeError
.
Example:
void main() {
dynamic x = 1;
String y = x;
}
Output: type 'int' is not a subtype of type 'String'
What exactly is a _TypeError? I can't find the documentation. I can't catch it (specifically) or expect it in a unit test.
Catching
The following is the only way I could catch it so far, but I don't want to catch 'em all. I want to use on ... catch(e)
., but on _TypeError catch(e)
doesn't work, because _TypeError
is undefined.
void main() {
dynamic x = 1;
try {
String y = x;
} catch (e) {
print('catched: ' e.runtimeType);
print(e.toString());
}
}
Output:
catched: _TypeError
type 'int' is not a subtype of type 'String'
Testing
How to expect it in a unit test? I expected this to work, but it doesn't:
test('throws a _TypeError', () {
dynamic x = 1;
String x;
expect(() => x = y, throwsException);
};
Output:
Expected: throws <Instance of 'Exception'>
Actual: <Closure: () => dynamic>
Which: threw _TypeError:<type 'int' is not a subtype of type 'String'>
CodePudding user response:
_TypeError
is an internal dart class used instead of TypeError
, so in most cases, you can just use TypeError
instead:
dynamic x = 1;
try {
String y = x;
} on TypeError catch (e) {
print('caught: ' e.runtimeType);
print(e.toString());
}
Testing
Sadly, I don't know of any way to test for TypeError, I don't believe they made a matcher for it, but I could be wrong, but I guess you could always test before the cast itself
test('throws a _TypeError', () {
dynamic y = 1;
String x;
expect(y, isInstanceOf<String>());
};
if the above test fails, so will x = y;