CodeBlanks Logo Icon CodeBlanks

Summary - Testing

Combine test, expect and mock to write a calculator test.

Summary: Testing

In this group you saw the dart test framework, test and expect, organization with group, fixtures with setUp/tearDown and mocks. Tests guarantee your code's correctness.

Now we combine them: we will write a testable Calculator class and print its result. This is the cornerstone of testing.

Remember: each test probes one behavior; setUp builds a clean environment; mocks keep external dependencies out.

Practice Calculator: add and subtract

Define a Calculator class with int add(int a, int b) => a + b; and int subtract(int a, int b) => a - b; methods. In main print the results of add(10, 3) and subtract(10, 3) on separate lines with print.

Starter code

main.dart
// Define the Calculator class (add, subtract)

void main() {
  // print the results of add(10, 3) and subtract(10, 3)
}

Sample solution

main.dart
class Calculator {
  int add(int a, int b) => a + b;
  int subtract(int a, int b) => a - b;
}

void main() {
  var c = Calculator();
  print(c.add(10, 3));
  print(c.subtract(10, 3));
}

Expected output

13
7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Concept matching

Term Meaning
test() Test block
expect() Assertion
group() Organization
setUp() Fixture

2 What does setUp provide?

  • Throws an error
  • A clean fixture Correct answer
  • Sets up a loop
  • Creates a mock

Explanation: setUp provides a clean fixture.

3 The expect matcher

Question
expect(result, ____(5));
Answer
expect(result, equals(5));

Explanation: equals(5) states the expected value.

All lessons in Intermediate