Exploration Of Unit Testing In Flutter
In this article, we will explore the Unit Testing in Flutter. How unit testing works, how we create the class and how the outcomes appear in your project.
If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.
Table Of Contents::
Run tests using IntelliJ or VSCode
Why is unit testing important?
So let’s start with it.
An introduction to Unit Testing:
Unit testing is a software testing technique by which individual units of source code sets of at least one computer program module along with related control information, use procedures, and operating methodology — are tested to decide if they are fit for use. Unit tests are commonly automated tests composed and run by software developers to guarantee that an application meets its plan and acts as intended.
In software testing, unit testing is a strategy for testing more isolated portions (or units) of code. Unit tests are generally directed with test automation scripts on the smallest testable portion of the software.
The unit is usually a function of the code. It is also a part of “white box testing,” which is a type of testing that can be written by someone who knows the architecture of the program.
This methodology can test code functions, strategies, or methods whether using procedural programming or object-oriented programming. If it depends on or converses with some other frameworks, it can’t be qualified as unit testing. The object is to guarantee that every unit of code functions true to form. This takes into consideration quality confirmation to write test cases just for bits of the software that influence the way of behaving of the framework.
Unit tests are handy for verifying the behavior of a single function, method, or class. The test package provides the core framework for writing unit tests, and the flutter_test package provides additional utilities for testing widgets.
Steps:
This recipe demonstrates the core features provided by the test
package using the following steps:
- Add the
test
orflutter_test
dependency. - Create a test file.
- Create a class to test.
- Write a
test
for our class. - Combine multiple tests in a
group
. - Run the tests.
> Add the test dependency:
The test
package provides the core functionality for writing tests in Dart. This is the best approach when writing packages consumed by web, server, and Flutter apps.
dev_dependencies:
test: <latest_version>
> Create a test file:
In this example, create two files: counter.dart
and counter_test.dart
.
The counter.dart
file contains a class that you want to test and resides in the lib
folder. The counter_test.dart
file contains the tests themselves and lives inside the test
folder.
In general, test files should reside inside a test
folder located at the root of your Flutter application or package. Test files should always end with _test.dart
, this is the convention used by the test runner when searching for tests.
When you’re finished, the folder structure should look like this:
counter_app/
lib/
counter.dart
test/
counter_test.dart
> Create a class to test:
Next, you need a “unit” to test. Remember: “unit” is another name for a function, method, or class. For this example, create a Counter
class inside the lib/counter.dart
file. It is responsible for incrementing and decrementing a value
starting at 0
.class Counter {
int value = 0; void increment() => value++; void decrement() => value–;
> Write a test for our class:
Inside the counter_test.dart
file, and write the first unit test. Tests are defined using the top-level test
function and you can check if the results are correct by using the top-level expect
function. Both of these functions come from the test
package.
// Import the test package and Counter class
import 'package:test/test.dart';
import 'package:counter_app/counter.dart';void main() {
test('Counter value should be incremented', () {
final counter = Counter(); counter.increment(); expect(counter.value, 1);
});
}
> Combine multiple tests in a group:
If you have several tests that are related to one another, combine them using the group
function provided by the test
package.
import 'package:test/test.dart';
import 'package:counter_app/counter.dart';void main() {
group('Counter', () {
test('value should start at 0', () {
expect(Counter().value, 0);
}); test('value should be incremented', () {
final counter = Counter(); counter.increment(); expect(counter.value, 1);
}); test('value should be decremented', () {
final counter = Counter(); counter.decrement(); expect(counter.value, -1);
});
});
}
> Run the tests:
Now that you have a Counter
class with tests in place, you can run the tests.
Run tests using IntelliJ or VSCode:
The Flutter plugins for IntelliJ and VSCode support running tests. This is often the best option while writing tests because it provides the fastest feedback loop as well as the ability to set breakpoints.
- > IntelliJ:-
- Open the
counter_test.dart
file - Select the
Run
menu - Click the
Run 'tests in counter_test.dart'
option
Alternatively, use the appropriate keyboard shortcut for your platform.
- > VSCode:-
- Open the
counter_test.dart
file - Select the
Run
menu - Click the
Start Debugging
option - Alternatively, use the appropriate keyboard shortcut for your platform.
Run tests in a terminal:
You can also use a terminal to run the tests by executing the following command from the root of the project:
flutter test test/counter_test.dart
For more options regarding unit tests, you can execute this command:
flutter test --help
Why is unit testing important?:
Unit testing is very important as it allows developers to detect bugs earlier in the lifecycle- thus improving the quality of delivered software. Here is a list of great benefits:
- > This methodology can reduce the overall impact on testing costs as bugs are caught in the early phases of development.
- > It allows better refactoring of code as it is more reliable code.
- > This practice also conditions developers to rethink how they code. Meaning, coding modular components that can be mocked if they do have dependencies.
- > Tests can be automated, which is extremely beneficial when maintaining code at scale.
- > Overall, it improves the quality of the code.
In DevOps, the process of continuous integration automatically runs tests against the code every time someone commits new code to the repository. If one test fails, the entire team can receive an email (or alert on Slack) of the break. Then the responsible person can rectify the issue.
Unit test example:
Here is a simple example of how to write unit tests.
Let’s say we’re trying to implement the sum
function. It takes two numbers a
and b
as its arguments and returns the number of the total amount.
def sum(a, b):
return a + b
The simplest way to write a unit test is by using the assert
function. This function can be found in most programming languages.
# It should pass
assert sum(1, 2) == 3
# It also should pass
assert sum(1, 2) != 0
Conclusion:
If you are performing automated tests consistently, you can see how beneficial unit testing is for catching bugs early on. Without this technique, a defect could make its way farther into the pipeline. Even worse, into production.
This means time and resources are allocated to finding, analyzing, and fixing defects when a simple automated test could have caught them. If your firm seeks a test automation tool to automatically catch bugs and alert developers via Slack.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.