databasedartservertddaqueduct

Aqueduct: Bad state: No entity found for '_MyEntity'. Did you forget to create a 'ManagedContext'?


I'm getting started on a new project and want to use test driven development.This is my entity:

import 'package:aqueduct/aqueduct.dart';

class MyEntity extends ManagedObject<_MyEntity> implements _MyEntity {}class _MyEntity {
  @primaryKey
  int id;
  int myValue;
}

I wanted to use MyEntity independently of the database while I extract some data from text files. But when I try to test it like this

void main() {
  test('DatabaseBuilder returns multiple entities', () {
    List<MyEntity> entities = [];
    entities.add(MyEntity());
    expect(entities.length, greaterThan(0));
  });
}

I get the following error:

Bad state: No entity found for '_MyEntity. Did you forget to create a 'ManagedContext'?

Am I not allowed to use the Entities for non-database logic?


Solution

  • This question was answered on the Aqueduct Slack channel so I am moving it here to be more easily searchable.

    Reductions answered:

    You will need to start a TestHarness with TestHarnessORMMixin mixed in. After that you can used the MnagedObject (sic) however you find fit.

    joeconwaystk followed up:

    Yes, what Reductions said… the framework handles TDD with the ORM by creating a temporary schema in your database server during testing (with the TestHarnessORMixin)

    So I updated the test/harness/app.dart file to look like this:

    class Harness extends TestHarness<MyChannel> with TestHarnessORMMixin {
      @override
      Future onSetUp() async {
        await resetData();
      }
    
      @override
      Future onTearDown() async {}
    
      @override
      ManagedContext get context => channel.context;
    }
    

    And my test to look like this:

    Future main() async {
      final harness = Harness()..install();
    
      test('DatabaseBuilder returns multiple entities', () {
        List<MyEntity> entities = [];
        entities.add(MyEntity());
        expect(entities.length, greaterThan(0));
      });
    }
    

    Even though I am not using the harness directly, installing it is enough to remove the error.

    If you don't like that method, another option I found is to create a model class that mirrors _MyEntity without extending ManagedObject:

    class MyEntityModel implements _MyEntity {
      @override
      int id;
    
      @override
      int myValue;
    }
    

    This could then be mapped over to MyEntity when actually inserting in the database. It seems better to just install the testing harness and use MyEntity directly, so that is what I did.

    For more help on setting up testing see this video and the documentation.