Repository navigation
Replies: 2 comments 1 reply
|
Hi! This is expected, although I agree it is not immediately obvious. TUnit.Mocks creates a derived class for class mocks. That means it can only intercept members that C# allows the generated class to override: In your first example, This is the same limitation found in conventional proxy-based .NET mocking frameworks such as Moq, NSubstitute, and FakeItEasy. Some specialized tools can intercept non-virtual methods by rewriting compiled code at runtime, but that is a different and heavier mechanism. For your desired behavior, public abstract class AbstractClass : IInterface
{
public void A(bool flag)
{
B();
}
public virtual void B()
{
// Real implementation
}
}Then the test can execute the real [Test]
public void MyTest()
{
var mock = AbstractClass.Mock();
mock.B().Callback(() =>
{
// Optional callback behavior
});
mock.Object.A(true);
mock.B().WasCalled(Times.AtLeastOnce);
}Because If you cannot change Thanks for raising this — I’ll make the class-mocking limitation clearer in the documentation. |
|
Here my new workaround with So here is what I added in my .csproj of my project under test : <ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).Tests"/>
</ItemGroup>and now I can have this multi interface to separate public exposed members and internal ones : public interface IInterface
{
void A(bool flag);
}
internal interface InternalInterface : IInterface
{
void B();
}
public abstract class AbstractClass : InternalInterface
{
public void A(bool flag)
{
B();
}
internal virtual void B()
{
// Real implementation
// 'Overridable' only internally
}
//Implementing InternalInterface B() method
void InternalInterface.B()
{
// Calling the virtual, internally overridable, B() method.
B();
}
}
[Test]
public async Task MyTest()
{
//Arrange
var mock = AbstractClass.Mock();
var mockedObject = mock.Object;
//Act
mockedObject.A(true);
//Assert
await Assert.That(mock.B).WasCalled();
} |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi. It might be my lack of understanding how mocking is supposed to work, but I was expecting I could mock a given class to get its methods implemented while allowing to setup any specific methods I want.
It appear only mocked interface methods and abstract / overridden one are 'setup-able' :
This is a simple example, but was I am dealing with could be something like :
I am using TUnit version 1.65.68.
All reactions