Nabs.Launchpad.Core.Testing
9.0.146
Prefix Reserved
dotnet add package Nabs.Launchpad.Core.Testing --version 9.0.146
NuGet\Install-Package Nabs.Launchpad.Core.Testing -Version 9.0.146
<PackageReference Include="Nabs.Launchpad.Core.Testing" Version="9.0.146" />
<PackageVersion Include="Nabs.Launchpad.Core.Testing" Version="9.0.146" />
<PackageReference Include="Nabs.Launchpad.Core.Testing" />
paket add Nabs.Launchpad.Core.Testing --version 9.0.146
#r "nuget: Nabs.Launchpad.Core.Testing, 9.0.146"
#:package Nabs.Launchpad.Core.Testing@9.0.146
#addin nuget:?package=Nabs.Launchpad.Core.Testing&version=9.0.146
#tool nuget:?package=Nabs.Launchpad.Core.Testing&version=9.0.146
Nabs Launchpad Core Testing Library
A comprehensive .NET 9 testing utilities library that provides a rich set of testing helpers, mocks, and extensions for unit testing, integration testing, and end-to-end testing within the Nabs Launchpad framework. This library streamlines common testing scenarios and promotes consistent testing practices across projects.
Features
- Test Case Factory: Structured test case creation with metadata support
- HTTP Client Mocking: Easy-to-use HTTP client mocking with fluent API
- Localization Testing: Mock string localizer for testing multilingual scenarios
- Playwright Integration: Enhanced Playwright test base classes for E2E testing
- Service Collection Testing: Extensions for testing dependency injection registration
- Verify.NET Integration: Preconfigured snapshot testing with Verify.NET
- Markup Testing: HTML markup formatting and testing utilities
- Property Analysis: Helpers for testing object properties and structure
Installation
This library is part of the Nabs Launchpad framework and is typically referenced as a project dependency:
<ProjectReference Include="..\Nabs.Launchpad.Core.Testing\Nabs.Launchpad.Core.Testing.csproj" />
Dependencies
Core Testing Dependencies
- Verify.XunitV3: Snapshot testing framework for .NET
- AwesomeAssertions: Enhanced assertion library
- Ardalis.Result: Result pattern implementation
- Bogus: Fake data generation library
- NSubstitute: Mocking framework
Integration Dependencies
- Microsoft.Playwright.TestAdapter: Playwright test adapter for browser testing
- HtmlAgilityPack: HTML parsing and manipulation
- Microsoft.Extensions.DependencyInjection.Abstractions: DI container abstractions
- Microsoft.Extensions.Localization.Abstractions: Localization abstractions
Quick Start
Setting up Verify Defaults
Configure Verify.NET with Launchpad-specific settings in your test startup:
// In test project initialization or test startup
DefaultTestSetting.ConfigureVerify();
Test Case Factory
Create structured test cases with metadata for better test organization:
[Fact]
public async Task Should_Process_User_Data()
{
// Arrange
var input = new UserRequest { Name = "John Doe" };
var expectedOutput = new UserResponse { Id = 123, Name = "John Doe" };
// Act
var result = await userService.ProcessAsync(input);
// Assert
var testCase = TestCaseFactory.Create<UserRequest, UserResponse>(1)
.WithName("Process Valid User")
.WithDescription("Should successfully process valid user data")
.WithWorkItem("PBI-123")
.WithInput(input)
.WithOutput(result);
await Verify(testCase);
}
HTTP Client Mocking
Mock HTTP responses for testing API clients:
public class ApiClientTests
{
private readonly HttpClient _httpClient;
public ApiClientTests()
{
var successResponse = Result.Success(new[]
{
new UserDto { Id = 1, Name = "John" },
new UserDto { Id = 2, Name = "Jane" }
});
_httpClient = MockHttpClientBuilder
.Create("https://api.example.com")
.ForRequest(HttpMethod.Get, "/api/users", HttpStatusCode.OK, successResponse)
.ForRequest(HttpMethod.Get, "/api/users/1", HttpStatusCode.OK,
Result.Success(new UserDto { Id = 1, Name = "John" }))
.Build();
}
[Fact]
public async Task Should_Get_Users_List()
{
// Arrange
var apiClient = new ApiClient(_httpClient);
// Act
var users = await apiClient.GetUsersAsync();
// Assert
users.Should().HaveCount(2);
}
}
Core Components
TestCase<TInput, TOutput>
A structured way to organize test data and metadata:
public sealed record TestCase<TInput, TOutput>
{
public int Scenario { get; }
public string? Name { get; set; }
public string? WorkItemId { get; set; }
public string? Description { get; set; }
public string? OutputDescription { get; set; }
public TInput? Input { get; set; }
public TOutput? Output { get; set; }
}
Features:
- Scenario numbering for test organization
- Work item tracking integration
- Input/output data capture
- Fluent configuration API
MockHttpClientBuilder
Fluent API for creating HTTP clients with predefined responses:
var httpClient = MockHttpClientBuilder
.Create("https://api.example.com")
.ForRequest(HttpMethod.Post, "/api/users", HttpStatusCode.Created,
Result.Success(new UserDto { Id = 123 }))
.ForRequest(HttpMethod.Get, "/api/users/123", HttpStatusCode.OK,
Result.Success(new UserDto { Id = 123, Name = "Test User" }))
.Build();
Features:
- Method and path-based request matching
- Ardalis.Result integration
- JSON serialization with camelCase naming
- Custom base address support
TestStringLocalizer
Mock implementation of IStringLocalizer
for testing localization:
var localizer = new TestStringLocalizer(new Dictionary<string, string>
{
["welcome.message"] = "Welcome, {0}!",
["error.notfound"] = "Resource not found"
});
// Usage in tests
var message = localizer["welcome.message", "John"];
Assert.Equal("Welcome, John!", message.Value);
Features:
- Dictionary-based resource lookup
- Format string support with parameters
- Fallback to key name when resource not found
- Support for
GetAllStrings()
enumeration
Service Collection Testing
Extensions for testing dependency injection registration:
[Fact]
public void Should_Register_Required_Services()
{
// Arrange
var services = new ServiceCollection();
var initialServices = services.ToArray();
// Act
services.AddMyCustomServices();
// Assert
var registeredServices = services.ToServiceTypeNames(initialServices);
registeredServices.Should().Contain([
"IUserService",
"IUserRepository",
"UserValidator"
]);
}
Features:
- Service type name extraction
- Filtering of baseline services
- Comparison helpers for before/after registration
Playwright Integration
Enhanced base classes for browser testing with improved lifecycle management:
PageTest
Base class for tests that need a browser page:
public class LoginPageTests : PageTest
{
[Fact]
public async Task Should_Login_Successfully()
{
// Arrange
await Page.GotoAsync("https://example.com/login");
// Act
await Page.FillAsync("[data-testid=username]", "testuser");
await Page.FillAsync("[data-testid=password]", "password123");
await Page.ClickAsync("[data-testid=login-button]");
// Assert
await Expect(Page).ToHaveURLAsync("https://example.com/dashboard");
}
}
ContextTest
Base class for tests that need a browser context (multiple pages):
public class MultiPageTests : ContextTest
{
public override BrowserNewContextOptions ContextOptions()
{
return new BrowserNewContextOptions
{
Locale = "en-NZ",
ColorScheme = ColorScheme.Dark,
ViewportSize = new() { Width = 1920, Height = 1080 }
};
}
}
BrowserTest
Base class for tests that need browser-level control:
public class BrowserConfigTests : BrowserTest
{
[Fact]
public async Task Should_Support_Multiple_Contexts()
{
// Arrange
var context1 = await NewContext();
var context2 = await NewContext();
// Act & Assert
var page1 = await context1.NewPageAsync();
var page2 = await context2.NewPageAsync();
// Contexts are isolated from each other
}
}
Features:
- Automatic browser lifecycle management
- Context isolation and cleanup
- Configurable browser options
- Worker-based service registration
- Exception-aware test state detection
Property Analysis Helpers
Test object structure and properties:
[Fact]
public void Should_Have_Expected_Properties()
{
// Act
var properties = AnaemicTestsHelpers.GetPropertyDefinitions<UserDto>()
.ToArray();
// Assert
properties.Should().Contain(p =>
p.Name == "Id" &&
p.TypeName == "Int32" &&
p.HasGetter &&
p.HasSetter);
}
Features:
- Property name and type extraction
- Getter/setter detection
- Support for inheritance hierarchies
- Useful for testing DTOs and domain objects
HTML Markup Testing
Format and validate HTML markup:
[Fact]
public void Should_Generate_Valid_HTML()
{
// Arrange
var rawHtml = "<div><p>Test content</p></div>";
// Act
var formattedHtml = rawHtml.ToHtml();
// Assert
formattedHtml.Should().Contain("<div>");
formattedHtml.Should().Contain("<p>Test content</p>");
}
Features:
- HTML formatting and indentation
- XML conversion for validation
- Integration with HtmlAgilityPack
- Useful for testing Blazor component output
Testing Best Practices
Verify.NET Configuration
The library preconfigures Verify.NET with sensible defaults:
// Applied automatically by DefaultTestSetting.ConfigureVerify()
VerifierSettings.UseStrictJson();
VerifierSettings.IgnoreMember<Exception>(e => e.TargetSite);
VerifierSettings.IgnoreMember("RowVersion");
Test Case Organization
Use the TestCase factory for complex scenarios:
[Theory]
[InlineData(1, "valid-data")]
[InlineData(2, "edge-case")]
[InlineData(3, "error-condition")]
public async Task Should_Handle_Various_Scenarios(int scenario, string description)
{
var testCase = TestCaseFactory.Create<string, Result>(scenario)
.WithDescription(description);
// Test implementation
await Verify(testCase).UseParameters(scenario);
}
HTTP Testing Patterns
Structure API client tests consistently:
public class ApiClientTestBase
{
protected HttpClient CreateMockClient()
{
return MockHttpClientBuilder
.Create()
.ForRequest(HttpMethod.Get, "/health", HttpStatusCode.OK, Result.Success("OK"))
.Build();
}
}
Integration with Launchpad Components
This library integrates with other Nabs Launchpad components:
- Core.Dtos: Test DTO properties and validation
- Core.ViewModels: Test view model behavior and data binding
- Core.Portal: Test Blazor components and user interactions
- Core.ServiceDefaults: Test service registration and configuration
- Core.SiloClient: Test Orleans grain client interactions
Advanced Usage
Custom Verify Settings
Extend the default Verify configuration:
[ModuleInitializer]
public static void InitializeVerify()
{
DefaultTestSetting.ConfigureVerify();
// Add custom settings
VerifierSettings.IgnoreMember("CreatedAt");
VerifierSettings.AddScrubber(text => text.Replace("localhost", "example.com"));
}
Playwright Service Registration
Use the worker service pattern for shared resources:
public class DatabaseTests : WorkerAwareTest
{
[Fact]
public async Task Should_Use_Shared_Database()
{
var dbService = await RegisterService("Database", () =>
Task.FromResult(new TestDatabaseService()));
// Use shared database across tests
}
}
Contributing
This library follows the Nabs Launchpad coding standards:
- Use C# 13 features and latest language constructs
- Follow nullable reference types conventions (
is null
,is not null
) - Implement proper async/await patterns
- Include comprehensive unit tests using the library itself
- Use file-scoped namespace declarations
- Apply proper XML documentation for public APIs
Testing Guidelines
xUnit v3 with Microsoft.Testing.Platform
- Use xUnit SDK v3 with Microsoft.Testing.Platform
- Always include "Arrange", "Act", "Assert" comments
- No mocking framework required for simple scenarios (use NSubstitute for complex mocks)
- Follow consistent test method naming and capitalization
- Avoid
Directory.SetCurrentDirectory
in tests to prevent concurrency issues
Verify.NET Best Practices
- Use snapshot testing for complex output verification
- Include scenario parameters in verify calls:
await Verify(result).UseParameters(scenario)
- Leverage the TestCase factory for metadata-rich tests
- Configure appropriate scrubbers for dynamic content
License
Copyright � Net Advantage Business Solutions
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net9.0
- Ardalis.Result (>= 10.1.0)
- AwesomeAssertions (>= 9.1.0)
- Bogus (>= 35.6.3)
- HtmlAgilityPack (>= 1.12.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.7)
- Microsoft.Extensions.Localization.Abstractions (>= 9.0.7)
- Microsoft.Playwright.TestAdapter (>= 1.54.0)
- NSubstitute (>= 5.3.0)
- Verify.XunitV3 (>= 30.5.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.