https://github.com/svetlova/static-mock
SMock is opensource lib for mocking static and instance methods and properties.
https://github.com/svetlova/static-mock
mock mocking moq static test testing tests unittesting unittests
Last synced: 5 months ago
JSON representation
SMock is opensource lib for mocking static and instance methods and properties.
- Host: GitHub
- URL: https://github.com/svetlova/static-mock
- Owner: SvetlovA
- License: mit
- Created: 2021-04-13T18:50:18.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2026-01-13T14:36:24.000Z (5 months ago)
- Last Synced: 2026-01-13T16:33:31.055Z (5 months ago)
- Topics: mock, mocking, moq, static, test, testing, tests, unittesting, unittests
- Language: C#
- Homepage: https://svetlova.github.io/static-mock/
- Size: 15.2 MB
- Stars: 14
- Watchers: 2
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Codeowners: .github/CODEOWNERS
Awesome Lists containing this project
README
# 🎯 SMock - Static & Instance Method Mocking for .NET
[](https://www.nuget.org/packages/SMock)
[](https://www.nuget.org/packages/SMock)
[](https://github.com/SvetlovA/static-mock/stargazers)
[](LICENSE)
[](https://dotnet.microsoft.com/)
**A mocking library that makes testing static methods easier!**
---
## Why SMock?
SMock breaks down the barriers of testing legacy code, third-party dependencies, and static APIs. Built on [MonoMod](https://github.com/MonoMod/MonoMod) runtime modification technology, SMock gives you the power to mock what others can't.
- **Mock Static Methods**: The only .NET library that handles static methods seamlessly
- **Two API Styles**: Choose Hierarchical (with validation) or Sequential (disposable) patterns
- **Zero Configuration**: Works with your existing test frameworks (NUnit, xUnit, MSTest)
- **Complete Feature Set**: Async/await, parameter matching, callbacks, exceptions, unsafe code
---
## Installation
### Package Manager
```powershell
Install-Package SMock
```
### .NET CLI
```bash
dotnet add package SMock
```
> 💡 **Pro Tip**: SMock works great with any testing framework - NUnit, xUnit, MSTest, you name it!
---
## 🚀 Quick Start
```csharp
// Mock a static method in just one line - Sequential API
using var mock = Mock.Setup(() => File.ReadAllText("config.json"))
.Returns("{ \"setting\": \"test\" }");
// Your code now uses the mocked value!
var content = File.ReadAllText("config.json"); // Returns test JSON
// Or use the Hierarchical API with inline validation
Mock.Setup(() => DateTime.Now, () =>
{
var result = DateTime.Now;
Assert.AreEqual(new DateTime(2024, 1, 1), result);
}).Returns(new DateTime(2024, 1, 1));
```
---
## Core Concepts
### Hook-Based Runtime Modification
SMock uses [MonoMod](https://github.com/MonoMod/MonoMod) to create **runtime hooks** that intercept method calls:
- **Non-Invasive**: No source code changes required
- **Isolated**: Each test runs in isolation
- **Fast**: Minimal performance overhead
- **Auto-Cleanup**: Hooks automatically removed after test completion
### Mock Lifecycle
```csharp
// 1. Setup: Create a mock for the target method
var mock = Mock.Setup(() => DateTime.Now);
// 2. Configure: Define return values or behaviors
mock.Returns(new DateTime(2024, 1, 1));
// 3. Execute: Run your code - calls are intercepted
var now = DateTime.Now; // Returns mocked value
// 4. Cleanup: Dispose mock (Sequential) or automatic (Hierarchical)
mock.Dispose(); // Or automatic with 'using'
```
---
## API Styles
SMock provides **two distinct API patterns** to fit different testing preferences:
### Sequential API
Perfect for **clean, scoped mocking** with automatic cleanup:
```csharp
[Test]
public void TestFileOperations()
{
// Mock file existence check
using var existsMock = Mock.Setup(() => File.Exists("test.txt"))
.Returns(true);
// Mock file content reading
using var readMock = Mock.Setup(() => File.ReadAllText("test.txt"))
.Returns("Hello World");
// Your code under test
var processor = new FileProcessor();
var result = processor.ProcessFile("test.txt");
Assert.AreEqual("HELLO WORLD", result);
} // Mocks automatically cleaned up here
```
### Hierarchical API
Perfect for **inline validation** during mock execution:
```csharp
[Test]
public void TestDatabaseConnection()
{
var expectedConnectionString = "Server=localhost;Database=test;";
Mock.Setup(context => DatabaseConnection.Connect(It.IsAny()), () =>
{
// This validation runs DURING the mock execution
var actualCall = DatabaseConnection.Connect(expectedConnectionString);
Assert.IsNotNull(actualCall);
Assert.IsTrue(actualCall.IsConnected);
}).Returns(new MockConnection { IsConnected = true });
// Test your service
var service = new DatabaseService();
service.InitializeConnection(expectedConnectionString);
}
```
---
## ⚡ Performance
SMock is designed for **minimal performance impact**:
- **Runtime Hooks**: Only active during tests
- **Zero Production Overhead**: No dependencies in production builds
- **Efficient Interception**: Built on MonoMod's optimized IL modification
- **Benchmarked**: Comprehensive performance testing with BenchmarkDotNet
### Performance Characteristics
| Operation | Overhead | Notes |
|-----------|----------|--------|
| **Mock Setup** | ~1-2ms | One-time cost per mock |
| **Method Interception** | <0.1ms | Minimal runtime impact |
| **Cleanup** | <1ms | Automatic hook removal |
| **Memory Usage** | Minimal | Temporary IL modifications only |
---
## ⚠️ Known Issues & Solutions
### Compiler Optimization Issue
If your mocks are not being applied and you're getting the original method behavior instead of the mocked behavior, this is likely due to compiler optimizations. The compiler may inline or optimize method calls, preventing SMock from intercepting them.
**Solutions**:
1. **Run tests in Debug configuration**:
```bash
dotnet test --configuration Debug
```
2. **Disable compiler optimization in your test project** by adding this to your `.csproj`:
```xml
false
```
3. **Disable optimization for specific methods** using the `MethodImpl` attribute:
```csharp
[Test]
[MethodImpl(MethodImplOptions.NoOptimization)]
public void MyTestMethod()
{
using var mock = Mock.Setup(() => File.ReadAllText("config.json"))
.Returns("{ \"setting\": \"test\" }");
// Your test code here
}
```
This issue typically occurs in Release builds where the compiler aggressively optimizes method calls. Using any of the above solutions will ensure your mocks work correctly.
---
## Additional Resources
- **[API Documentation](https://svetlova.github.io/static-mock/api/index.html)**
- **[More Examples](https://github.com/SvetlovA/static-mock/tree/master/src/StaticMock.Tests/Tests)**
- **[Hierarchical API Examples](https://github.com/SvetlovA/static-mock/tree/master/src/StaticMock.Tests/Tests/Hierarchical)**
- **[Sequential API Examples](https://github.com/SvetlovA/static-mock/tree/master/src/StaticMock.Tests/Tests/Sequential)**
---
## 📄 License
This library is available under the [MIT license](https://github.com/SvetlovA/static-mock/blob/master/LICENSE).
---
## 🚀 Ready to revolutionize your .NET testing?
**[⚡ Get Started Now](#installation)** | **[📚 View Examples](https://github.com/SvetlovA/static-mock/tree/master/src/StaticMock.Tests/Tests)** | **[💬 Join Discussion](https://github.com/SvetlovA/static-mock/discussions)**
---
*Made with ❤️ by [@SvetlovA](https://github.com/SvetlovA) and the SMock community*