TUnit: Using hooks in generic class gives compiler errors

When using a base class with a generic parameter, using a hook generates some invalid source code. Having this example class:

public abstract class RepositoryTest<TRepository>
    where TRepository : notnull
{
    protected TRepository Repository => Resolve<TRepository>();

    [After(Test)]
    public Task TearDown()
    {
        return HostFixture.Cleanup();
    }
    
    protected static T Resolve<T>()
        where T : notnull
    {
        return HostFixture.Host.Scope.Resolve<T>();
    }
}

We get this generated code:

public global::System.Collections.Generic.IReadOnlyList<InstanceHookMethod> CollectAfterTestHooks(string sessionId)
{
    return
    [
    	new InstanceHookMethod<global::Rapidata.Tests.Shared.MongoDB.RepositoryTest<TRepository>>
    	{
    		MethodInfo = global::TUnit.Core.Helpers.MethodInfoRetriever.GetMethodInfo(typeof(global::Rapidata.Tests.Shared.MongoDB.RepositoryTest<TRepository>), "TearDown", 0, []),
    		AsyncBody = (classInstance, context, cancellationToken) => AsyncConvert.Convert(() => classInstance.TearDown()),
    		HookExecutor = DefaultExecutor.Instance,
    		Order = 0,
    		MethodAttributes = [ new global::TUnit.Core.AfterAttribute(global::TUnit.Core.HookType.Test)
    {
    
    } ],
    		ClassAttributes = [  ],
    		AssemblyAttributes = [  ],
    	},
    ];
}

This generated code references the type TRepository, which doesn’t exist in that context. To circumvent this, one could create an additional base class where the hooks are placed and have the generic parts in a sub-abstract class. Is there a way to support this scenario without an additional base class?

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16 (7 by maintainers)

Most upvoted comments