Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions Docs/pages/advanced-features/02-static-interface-members.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,47 @@
# Static interface members (.NET 8+)
# Static interface members

Mockolate supports mocking static abstract and static virtual members on interfaces (.NET 8+). Static member
invocations use async-flow scoping, meaning each mock instance has its own isolated static member context, this makes parallel test execution safe.

Static members can be set up, raised, and verified just like instance members, but through the `Mock.SetupStatic`, `Mock.RaiseStatic`, and `Mock.VerifyStatic` properties:

**Example**

```csharp
public interface IChocolateFactory
{
static abstract string DefaultRecipe { get; set; }
static abstract int ProduceBatch(string type, int amount);
static abstract event Action<int> BatchCompleted;
}

IChocolateFactory sut = IChocolateFactory.CreateMock();

// Setup static members
sut.Mock.SetupStatic.AbstractStaticMethod().Returns("some-value");
sut.Mock.SetupStatic.AbstractStaticProperty.Returns("some-value");
sut.Mock.SetupStatic.ProduceBatch(It.Is("Dark"), It.IsAny<int>()).Returns(42);
sut.Mock.SetupStatic.DefaultRecipe.Returns("Dark");

// Raise static events
sut.Mock.RaiseStatic.AbstractStaticEvent(value);
// Static abstract members can only be invoked through a generic type parameter,
// so route the call through a helper constrained to the interface and pass the
// generated mock type (Mock.IChocolateFactory) as the type argument.
string recipe = ReadRecipe<Mock.IChocolateFactory>();
int produced = Produce<Mock.IChocolateFactory>("Dark", 10);
Subscribe<Mock.IChocolateFactory>(amount => Console.WriteLine($"Batch of {amount} ready"));

// Raise static events to the registered handlers
sut.Mock.RaiseStatic.BatchCompleted(produced);

// Verify static interactions
sut.Mock.VerifyStatic.AbstractStaticMethod().Once();
sut.Mock.VerifyStatic.AbstractStaticProperty.Got().Once();
sut.Mock.VerifyStatic.AbstractStaticEvent.Subscribed().Once();
sut.Mock.VerifyStatic.ProduceBatch(It.Is("Dark"), It.IsAny<int>()).Once();
sut.Mock.VerifyStatic.DefaultRecipe.Got().Once();
Comment thread
vbreuss marked this conversation as resolved.
sut.Mock.VerifyStatic.BatchCompleted.Subscribed().Once();
Comment thread
vbreuss marked this conversation as resolved.

static string ReadRecipe<T>() where T : IChocolateFactory
=> T.DefaultRecipe;
static int Produce<T>(string type, int amount) where T : IChocolateFactory
=> T.ProduceBatch(type, amount);
static void Subscribe<T>(Action<int> handler) where T : IChocolateFactory
=> T.BatchCompleted += handler;
```

**Notes:**
Expand Down
Loading