3

假设我有一个具有一些类似属性的类:

public string First { get; set; }
public string Second { get; set; }
public string Third { get; set; }

我想在我的测试中以同样的方式测试它们......所以我写道:

[Test]
public void TestFirst()
{
    // Asserting strings here
}

有没有办法避免创建三个测试(一个用于第一个,一个用于第二个,一个用于第三个)?

我正在寻找类似的东西[Values(First, Second, Third)],所以我可以编写一个迭代属性的测试。

干杯,并提前感谢:)

4

7 回答 7

2

How about this:

[TestFixture]
public class Tests
{
    [Test]
    public void Test()
    {
        var obj = new MyClass();

        obj.First = "some value";
        obj.Second = "some value";
        obj.Third = "some value";

        AssertPropertyValues(obj, "some value", x => x.First, x => x.Second, x => x.Third);
    }

    private void AssertPropertyValues<T, TProp>(T obj, TProp expectedValue, params Func<T, TProp>[] properties)
    {
        foreach (var property in properties)
        {
            TProp actualValue = property(obj);
            Assert.AreEqual(expectedValue, actualValue);
        }
    }
}
于 2013-01-15T07:02:01.953 回答
1

这样做很容易,但我质疑这是否值得。

如何 - 上面的许多答案都有效,但这似乎最简单,假设您正在测试一个新创建的对象......

[TestCase("First", "foo"]
[TestCase("Second", 42]
[TestCase("Third", 3.14]
public void MyTest(string name, object expected)
{
    Assert.That(new MyClass(), Has.Property(name).EqualTo(expected));
}

但是,在测试中放置三个单独的断言似乎更容易阅读......

[Test]
public void MyTest()
{
    var testObject = new MyClass();
    Assert.That(testObject, Has.Property("First").EqualTo("foo"));
    Assert.That(testObject, Has.Property("Second").EqualTo(42));
    Assert.That(testObject, Has.Property("Third").EqualTo(3.14));
}

当然,这假设三个断言都是测试一件事的一部分,例如 DefaultConstructorInitializesMyClassCorrectly。如果这不是您要测试的内容,那么三个测试更有意义,即使它需要更多的输入。确定的一种方法是查看您是否能够为测试想出一个合理的名称。

查理

于 2013-01-17T02:15:40.567 回答
1

您应该能够为此目的使用表达式树。使用Expression.Property方法的 MSDN 文档,我创建了以下辅助方法,用于获取从任意对象T命名的类型属性:propertyNameobj

public T InvokePropertyExpression<T>(object obj, string propertyName)
{
    return Expression.Lambda<Func<T>>(Expression.Property(
               Expression.Constant(obj), propertyName)).Compile()();
}

在我的单元测试中使用这个辅助方法,我现在可以根据其名称访问相关属性,例如:

[Test, Sequential]
public void Tests([Values("First", "Second", "Third")] string propertyName,
                  [Values("hello", "again", "you")] string expected)
{
    var obj = new SomeClass 
        { First = "hello", Second = "again", Third = "you" };
    var actual = InvokePropertyExpression<string>(obj, propertyName);
    Assert.AreEqual(expected, actual);
}
于 2013-01-15T08:40:37.970 回答
1

使用 . 来表达这种断言有很多可能性NUnit.Framework.Constraints.Constraint。此外,您可以使用or为测试描述更多输入,而不是使用ValuesAttributeorTestCaseAttributeValuesSoueceAttributeTestCaseSourceAttribute

描述测试输入

让我们使用来定义预期的属性名称和它们的值TestCaseSourceAttribute

public IEnumerable TestCasesSourcesAllProperties
{
    get
    {
        yield return new TestCaseData(
            new Tuple<string, string>[] { 
                Tuple.Create("First", "foo"), 
                Tuple.Create("Second", "bar"), 
                Tuple.Create("Third", "boo") } as object)
                    .SetDescription("Test all properties using Constraint expression");
    }
}

在单个测试中构建约束

现在我们可以在一个测试中为所有三个属性建立约束

// get test parameters from TestCasesSourcesAllProperties
[TestCaseSource("TestCasesSourcesAllProperties")]
public void ClassUnderTest_CheckAllProperty_ExpectValues(Tuple<string, string>[] propertiesNamesWithValues)
{
    // Arrange
    ClassUnderTest cut = null;

    // Act: perform actual test, here is only assignment
    cut = new ClassUnderTest { First =  "foo", Second = "bar",  Third  = "boo" };

    // Assert
    // check that class-under-test is not null
    NUnit.Framework.Constraints.Constraint expression = Is.Not.Null;

    foreach(var property in propertiesNamesWithValues)
    {
        // add constraint for every property one by one
        expression = expression.And.Property(property.Item1).EqualTo(property.Item2);
    }

    Assert.That(cut, expression);
}

这是一个完整的例子

缺点

配置逻辑,即foreach内部测试逻辑

于 2013-01-15T12:24:10.920 回答
0

您可以编写参数化测试并将属性访问器作为参数传递:

请参阅示例:假设您的具有 3 个属性的类是:

public class MyClass
{
    public string First { get; set; }
    public string Second { get; set; }
    public string Third { get; set; }
}

然后测试可能看起来:

[TestFixture]
public class MyTest
{
    private TestCaseData[] propertyCases = new[]
        {
            new TestCaseData(
                "First",
                (Func<MyClass, string>) (obj => obj.First),
                (Action<MyClass, string>) ((obj, newVal) => obj.First = newVal)),

            new TestCaseData(
                "Second",
                (Func<MyClass, string>) (obj => obj.Second),
                (Action<MyClass, string>) ((obj, newVal) => obj.Second = newVal)),

            new TestCaseData(
                "Third",
                (Func<MyClass, string>) (obj => obj.Third),
                (Action<MyClass, string>) ((obj, newVal) => obj.Third = newVal))
        };

    [Test]
    [TestCaseSource("propertyCases")]
    public void Test(string description, Func<MyClass, string> getter, Action<MyClass, string> setter)
    {
        var obj = new MyClass();
        setter(obj, "42");

        var actual = getter(obj);

        Assert.That(actual, Is.EqualTo("42"));
    }
}

几点注意事项:
1. 未使用的字符串描述作为第一个参数传递,以区分通过 NUnit 测试运行器 UI 或 Resharper 运行的测试用例。
2. Tet 案例是独立的,即使First属性测试失败,其他 2 个测试也会运行。
3. 可以通过 NUnit 测试运行器 UI 或通过 Resharper 单独运行一个测试用例。

所以,你的测试是干净和干燥的 :)

于 2013-01-15T18:17:29.253 回答
0

您可以Values在测试方法的参数上使用该属性:

[Test]
public void MyTest([Values("A","B")] string s)
{
    ...
}

但是,这仅适用于字符串常量(即不适用于属性值)。

我想您可以使用反射从给定值中获取属性值,例如

[Test]
public void MyTest([Values("A","B")] string propName)
{
    var myClass = new MyClass();
    var value = myClass.GetType().GetProperty(propName).GetValue(myClass, null);

    // test value
}

但这并不是最干净的解决方案。也许您可以编写一个测试,调用一个方法来测试每个属性。

[Test]
public void MyTest()
{
    var myClass = new MyClass();
    MyPropertyTest(myClass.First);
    MyPropertyTest(myClass.Second);
    MyPropertyTest(myClass.Third);
}

public void MyPropertyTest(string value)
{
    // Assert on string
}

但是,最好避免这种测试方式,因为单元测试应该这样做 - 测试代码单元。如果每个测试都被正确命名,它可以用来记录您所期望的,并且可以在将来轻松添加。

于 2013-01-15T06:54:21.087 回答
0

感谢大家的回答和帮助。学到了很多东西。

这就是我最终要做的。我已经使用反射来获取所有字符串属性,然后设置为一个值,检查值是否设置,设置为 null,检查它是否返回一个空字符串(属性的 getter 中的逻辑)。

[Test]
public void Test_AllStringProperties()
{
    // Linq query to get a list containing all string properties
    var string_props= (from prop in bkvm.GetType()
                            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                      where
                        prop.PropertyType == typeof(string) &&
                        prop.CanWrite && prop.CanRead
                      select prop).ToList();

    string_props.ForEach(p =>{
                                 // Set value of property to a different string
                                 string set_val = string.Format("Setting [{0}] to: \"Testing string\".", p.Name);
                                 p.SetValue(bkvm, "Testing string", null);
                                 Debug.WriteLine(set_val);
                                 // Assert it was set correctly
                                 Assert.AreEqual("Testing string", p.GetValue(bkvm, null));

                                 // Set property to null
                                 p.SetValue(bkvm,null,null);
                                 set_val = string.Format("Setting [{0}] to null. Should yield an empty string.", p.Name);
                                 Debug.WriteLine(set_val);
                                 // Assert it returns an empty string.
                                 Assert.AreEqual(string.Empty,p.GetValue(bkvm, null));
                             }
        );
}

这样我就不需要担心是否有人添加了一个属性,因为它会被自动检查,而不需要我更新测试代码(正如你可能猜到的,不是每个人都更新或编写测试:)

欢迎对此解决方案提出任何意见。

于 2013-01-21T04:02:15.000 回答