Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test source_gen annotation builders using testBuilder?

Tags:

dart

I have a code generator made using source_gen. It is working properly, but I would like to add tests.

I followed the documentation and took inspiration from built_value by using testBuilder from build_test.

The problem is, when using testBuilder, it cannot properly resolve imports. And therefore throws an error and doesn't trigger my generator.

Error: line 1, column 91 of asset:example/lib/src/truc.dart: Could not resolve annotation for foo() → dynamic\n'

Here's my current test attempt :

import 'package:source_gen/source_gen.dart';
import 'package:test/test.dart';
import 'package:build_test/build_test.dart';
import 'package:my_gen/my_gen.dart';

const input = {
  "example|lib/src/foo.dart": '''
import 'package:my_gen/my_gen.dart';
import 'package:flutter/material.dart';

@stateless
Widget foo() {
  return Center();
}
'''
};

void main() {
  test('', () async {
    await testBuilder(SharedPartBuilder([MyGenerator], "stateless"), input, outputs: {
      "example|lib/src/foo.stateless.g.part": '''
// **************************************************************************
// StatelessGenerator
// **************************************************************************

class Foo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return foo();
  }
}
'''
    });
  });
}

How can I make testBuilder to properly resolve import; and ultimately test by generator?

like image 618
Rémi Rousselet Avatar asked Apr 28 '26 06:04

Rémi Rousselet


1 Answers

Look at what we do in json_serializable - https://github.com/dart-lang/json_serializable/blob/master/json_serializable/test/json_serializable_test.dart

We don't use build_test. Instead we have a utility library that gets a library reader you can use for testing - https://github.com/dart-lang/json_serializable/blob/master/json_serializable/test/analysis_utils.dart

like image 64
Kevin Moore Avatar answered May 01 '26 16:05

Kevin Moore