VerifySettings.Context is a dictionary that carries information from a test to the extension points that run during a verification. It is exposed as IReadOnlyDictionary<string, object> to:
- Comparers
- Converters
- Scrubbers
- AppendFile and JsonAppender delegates
It is also exposed as VerifyJsonWriter.Context to serialization converters.
Those extension points are registered globally, and are shared by every test. Context is how a single test passes state to them, for example an environment name or a feature flag.
Values are written to the dictionary on the settings used for the verification:
[Fact]
public Task ComparerWithContext()
{
var settings = new VerifySettings
{
Context =
{
["featureEnabled"] = true
}
};
settings.UseStringComparer(Compare, "txt");
return Verify("TheText", settings);
}Or fluently, via AddContext:
[Fact]
public Task ComparerWithContextFluent() =>
Verify("TheText")
.AddContext("featureEnabled", true)
.UseStringComparer(Compare, "txt");And read in the extension point:
static Task<CompareResult> Compare(
string received,
string verified,
IReadOnlyDictionary<string, object> context)
{
if (context.TryGetValue("featureEnabled", out var value) &&
value is true)
{
// Drop the flagged content from both sides before comparing
return Task.FromResult(
new CompareResult(RemoveFlagged(received) == RemoveFlagged(verified)));
}
return Task.FromResult(new CompareResult(received == verified));
}
static string RemoveFlagged(string value) =>
string.Join(
'\n',
value
.Split('\n')
.Where(_ => !_.Contains("FeatureFlagged")));Values that are the same for every test do not need Context. A static field is sufficient in that case. Context matters where the value varies per test.
Verify uses the same dictionary for some per-verification state, under keys prefixed with Verify.. For example ExcludeTargets stores its extensions under Verify.ExcludeTargets, which is what allows a converter to call context.IsTargetExcluded("png"). Keys prefixed with Verify. should be treated as reserved.
When settings are copied, for example when a VerifySettings instance is passed to a fluent API, the context is copied entry by entry. Entries implementing ICloneable are cloned, and all other entries are copied by reference.