gpt4 book ai didi

c# - 如何从 TestContext 获取当前参数值?

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:23 24 4
gpt4 key购买 nike

我有一个单元测试:

[Test]
[TestCaseSource(typeof(AllExampleEnumValues))]
public void GivenSth_WhenSth_ThenSth(ExampleEnum enumValue)
{
// Given
var givenState = BaseClassProperty; // property from fixture's base class
systemUnderTest.SetSomeState(givenState);

// When
var result = systemUnderTest.AnswerAQuestion(
"What's the answer to"
+ " the Ultimate Question of Life,"
+ " the Universe,"
+ " and Everything?");

// Then
Assert.That(result, Is.EqualTo(42));
}

其中 AllExampleEnumValues 如下:

public class AllGranularities : IEnumerable
{
public IEnumerator GetEnumerator()
{
return Enum
.GetValues(typeof(ExampleEnum))
.Cast<ExampleEnum>()
.Select(ee => new object[] { ee })
.GetEnumerator();
}
}

在基类中我有:

protected int BaseClassProperty
{
get
{
return //depending on enumValue
}
}

如何在 BaseClassProperty 运行时获取 enumValue 参数的当前值,而不将其更改为函数并将 enumValue 作为参数?

我知道我可以以某种方式遍历堆栈框架并从那里读取它(不,实际上,我不能:How can I get the values of the parameters of a calling method?),但也许有更优雅的解决方案?

我需要它来提高测试的可读性——enumValue 会影响读取 BaseClassProperty 的结果的事实不会降低可读性,因为在我的领域中这种依赖有目共睹。

我一直在研究 TextContext 类,但它似乎在此上下文中没有任何用处。如评论中所述,该值出现在测试的名称中 - 但是从字符串解析值在这里是 Not Acceptable ,因为有时我们使用多个参数和通用测试用例。

另一条线索导致使用 IApplyToTest 属性。然而,这需要将此属性应用于每个测试。

最后,另一条线索导致使用 ITestAction,从内部我可以访问 ITest 接口(interface),它提供了一个 TestMethod 实例。它具有 Arguments 属性!不幸的是 - 它是私有(private)的。

最佳答案

我已经设法创建了以下解决方法:

[AttributeUsage(AttributeTargets.Class)]
public class TrackEnumValueActionAttribute : Attribute, ITestAction
{
public ActionTargets Targets
{
get
{
return ActionTargets.Test;
}
}

public void AfterTest(ITest test)
{
}

public void BeforeTest(ITest test)
{
if (!(test.Fixture is ICurrentExampleEnumValueHolder))
{
return;
}

var arguments = GetArgumentsFromTestMethodOrNull(test);

if (arguments == null)
{
return;
}

var eumValue = GetEnumValueFromArgumentsOrNull<ExampleEnum>(arguments);

(test.Fixture as ICurrentExampleEnumValueHolder).CurrentEnumValue = enumValue;
}

private object[] GetArgumentsFromTestMethodOrNull(ITest test)
{
return test
.GetType()
.GetProperty("Arguments", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
?.GetValue(test) as object[];
}

private T? GetEnumValueFromArgumentsOrNull<T>(object[] arguments) where T : struct
{
return arguments
.Where(a => a.GetType().Equals(typeof(T)))
.Select(a => (T?)a)
.FirstOrDefault();
}
}

将此属性应用于我的夹具的基类,并实现 ICurrentExampleEnumValueHolder 接口(interface)就可以了——我的属性值(存在于接口(interface)中)的值取决于测试方法调用参数。

不幸的是,NUnit 中 TestMethod 类的 Arguments 属性是内部的,因此存在丑陋的反射解决方法。我已经发布了关于此事的问题:https://github.com/nunit/nunit/issues/2079

关于c# - 如何从 TestContext 获取当前参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com