Skip to content

[Bug]: Mock a class with its constructor calling a mocked method result in Null MockEngine exception #6734

Description

@elTRexx

Description

When mocking a class which have its constructor calling a method that itself is also mocked (being virtual / abstract), cause the MockEngine _engine field in the generated mock implementation not being set in time when already calling the base() constructor that in turn call the mocked method :

Expected Behavior

The MockEngine _engine field should be set before calling base() constructor

Actual Behavior

The base() constructor is called before MockEngine _engine field have been set.

Steps to Reproduce

public class MyClass
{
  public MyClass() 
  {
    A();
  }

  public virtual void A()
  { }
}

[Test]
public async Task MyTest()
{
  var mock = MyClass.Mock();

  mock.Object.A();

  await Assert.That(mock.A).WasCalled();
}

See in debugging steps that in source generated file sealed class StateTests_MyClassMockImpl file
its constructor

  1. call the base() constructor
  2. MyClass constructor call A()
  3. mocked StateTests_MyClassMockImpl.A() method is then called
  4. NullReferenceException is thrown on _engine field

TUnit Version

1.65.68

.NET Version

.Net 9.0 C#14 preview

Operating System

Windows

IDE / Test Runner

Visual Studio

Error Output / Stack Trace

[Null Reference] Object reference not set to an instance of an object.

Additional Context

No response

IDE-Specific Issue?

  • I've confirmed this issue occurs when running via dotnet test or dotnet run, not just in my IDE

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is needed

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions