Unit Test in Flutter

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.
No alt text provided for this image

  • 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.
No alt text provided for this image

要查看或添加评论,请登录

Bhushan Jadhav的更多文章

  • Dart Extension

    Dart Extension

    Hello guys!! In this article you will learn how to use extension in dart. After reading this article you will be able…

    1 条评论
  • Generics in dart

    Generics in dart

    Hello! In this article, you’ll learn how to use the Dart generics. After reading this article you can easily use dart…

    2 条评论
  • How to use Native code in Flutter

    How to use Native code in Flutter

    Hello FlutterDevs, In this article we will learn, How we can use Native code in our Flutter Project for Android and i…

  • How to connect Firebase to our Flutter project

    How to connect Firebase to our Flutter project

    In this article i will teach you how we can connect Firebase to our Flutter project just follow all the steps given…

社区洞察

其他会员也浏览了