Unit Test in Flutter
Hello guys in this article we are going to learn how to write Unit test in Flutter .
Unit test plays a very important role in development that's why we should write unit test for complex method. If in future any other developer saw our code so they will get good understanding of our code by running unit test.
- First of all We will create a counter.dart file inside a lib folder.
- Paste the below code snippet in counter.dart file .
class Counter {
int value = 0;
void increment() => value++;
void decrement() => value--;
}
In Counter class we are just incrementing decrementing value by 1.
- Now, create a new file counter_test.dart in inside the test folder. In flutter we have to write all our test in inside the test folder.
void main() {
test('Counter value should be incremented', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
}
- Copy and paste above code in counter_test.dart file.
领英推è
- test function is given by flutter we have to write our test inside the test function, It takes two parameter the First is string In which we have to write description of test, and the Second parameter it take is Function In which we will write a test for our Counter class.
- expect takes also two parameter the first one is actual value which we are getting in this case it is counter.value, and the second parameter is what value we want, For example in this example we are calling increment function so after calling increment function counter.value will become 1 and the second parameter we are passing is also 1 so in this condition this test is passes.
- In simple word this test is passes if and only if both the parameter of expect is same. If anyone of them is different then test will fail.
We can run the test by following command.
flutter test test/counter_test.dart
We did it guys if you need any help then you can connect with me on Linkedin.