Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test an assertion?

I found out how you can test an exception or error: https://stackoverflow.com/a/54241438/6509751

But how do I test that the following assert works correctly?

void cannotBeNull(dynamic param) {
  assert(param != null);
}

I tried the following, but it does not work. The assertion is simply printed out and the test fails:

void main() {
  test('cannoBeNull assertion', () {
    expect(cannotBeNull(null), throwsA(const TypeMatcher<AssertionError>()));
  });
}
like image 589
creativecreatorormaybenot Avatar asked Oct 14 '19 19:10

creativecreatorormaybenot


People also ask

What is assert testing?

At the basic level, an assertion is just a Boolean expression. It contains a true and false binary. The expression is placed into the testing program and pertains to a certain section of the software being tested. The assertion itself encompasses an expression that describes the logic of the code under test.

What is the example of assertion?

An example of someone making an assertion is a person who stands up boldly in a meeting with a point in opposition to the presenter, despite having valid evidence to support his statement. An example of an assertion was that of ancient scientists that stated the world was flat.

What is an assertion in unit testing?

Assertions replace us humans in checking that the software does what it should. They express the requirements that the unit under test is expected to meet. Assert the exact desired behavior; avoid overly precise or overly loose conditions.


1 Answers

There are two key aspects to this:

  • Pass a callback to expect. When you do that, you can never do something wrong, even if you just instantiate an object. This was already shown in the linked answer.

  • Use throwAssertionError.

Example:

expect(() {
  assert(false);
}, throwsAssertionError);

Applied to the code from the question:

void main() {
  test('cannoBeNull assertion', () {
    expect(() => cannotBeNull(null), throwsAssertionError);
  });
}

Why do we need to pass a callback? Well, if you have a function without parameters, you can also pass a reference to that as well.

If there was no callback, the assertion would be evaluated before expect is executed and there would be no way for expect to catch the error. By passing a callback, we allow expect to call that callback, which allows it to catch the AssertionError and it is able to handle it.

like image 132
creativecreatorormaybenot Avatar answered Sep 19 '22 14:09

creativecreatorormaybenot