Skip to content

Instantly share code, notes, and snippets.

@d1820
Last active January 13, 2024 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d1820/51fa8d238aaf2e208f917dbd5199a502 to your computer and use it in GitHub Desktop.
Save d1820/51fa8d238aaf2e208f917dbd5199a502 to your computer and use it in GitHub Desktop.
Running XUNIT Tests that need a static implementation of a class
public class CommentHelperTests: IClassFixture<TestFixture>
{
private readonly TestFixture fixture;
public CommentHelperTests(TestFixture fixture, ITestOutputHelper output)
{
this.fixture = fixture;
this.fixture.Initialize(output);
}
[Fact]
public void SpilitNameAndToLower_KeepsAllUpperCaseWordsInProperCasing()
{
fixture.RegisterCallback(nameof(SpilitNameAndToLower_KeepsAllUpperCaseWordsInProperCasing), (o) => o.ExcludeAsyncSuffix = true);
var result = tHelper.SpilitNameAndToLower("ExecuteOCRActionAsync", true);
result.Count.Should().Be(3);
}
[Fact]
public void SpilitNameAndToLower_KeepsAllUpperCaseWordsInProperCasingAddsAsyncToListWhenOptionFalse()
{
fixture.RegisterCallback(nameof(SpilitNameAndToLower_KeepsAllUpperCaseWordsInProperCasingAddsAsyncToListWhenOptionFalse), (o) => o.ExcludeAsyncSuffix = false);
var result = Helper.SpilitNameAndToLower("ExecuteOCRActionAsync", true);
result.Count.Should().Be(4);
result[0].All(a => char.IsLower(a)).Sho
}
}
public class TestFixture
{
private Container _testContainer;
public string CurrentTestName { get; set; }
protected static ConcurrentDictionary<string, Action<IOptionsService>> RegisteredCallBacks = new ConcurrentDictionary<string, Action<IOptionsService>>();
public TestFixture()
{
}
public void Initialize(ITestOutputHelper output)
{
CurrentTestName = output.GetTestName();
_testContainer = new Container();
_testContainer.Register<IOptionsService>(() =>
{
var os = new TestOptionsService();
if (CurrentTestName != null && RegisteredCallBacks.TryGetValue(CurrentTestName, out var callback))
{
callback.Invoke(os);
}
return os;
}, Lifestyle.Transient);
Static.DIContainer(_testContainer);
}
public void RegisterCallback(string name, Action<IOptionsService> callback)
{
RegisteredCallBacks.TryAdd(name, callback);
}
}
public static class TestFixtureExtensions
{
public static string GetTestName(this ITestOutputHelper output, bool returnFullName = false)
{
var type = output.GetType();
var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic);
var test = (ITest)testMember.GetValue(output);
var name = test.DisplayName.Split('(').First();
return returnFullName ? name : name.Split('.').Last();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment