Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test DART's runApp() function

I can't reach 100% test coverage because of DART's runApp() function. I tried to create tests for this function, but couldn't. Has anyone created a test for this function?

void main() => runApp(MyApp());

My coverage is 96.2% because only one line with the runApp() function has no test.

I would like to know how to create a unit test for this function.

enter image description here

Project source: full_testing_flutter

like image 725
Chinnon Santos Avatar asked Sep 01 '25 20:09

Chinnon Santos


2 Answers

You can use comments to tell the coverage calculator to ignore lines:

// coverage:ignore-start
void main() => runApp(MyApp());
// coverage:ignore-end

I wouldn't recommend letting this strategy permeate the rest of your code, but for this simple one-off, it seems fine.

like image 85
Alex P Avatar answered Sep 03 '25 15:09

Alex P


The strategy I've used is to avoid calling the runApp method directly in my code altogether.

You can do this by keeping your code as declarative as possible.

Instead of:

void main() => runApp(MyApp());

Use something like:

import 'package:flutter/material.dart'

void main() => AppRunner(
    widget: MyApp(),
    runMethod: runApp,
).run;

class AppRunner{
    AppRunner({
        required this.widget,
        required this.runMethod,
    });

    final Widget widget;
    final Function(Widget) runMethod;

    void run() => runMethod(widget);
}

You will also want to test that that your AppRunner's run method executes the runMethod parameter with the given widget parameter to get it to 100%.

like image 31
Martin Gagne Avatar answered Sep 03 '25 15:09

Martin Gagne