是否可以使用Func或Action< T>为了达到这个目的

本文关键字:可以使 Func 是否 result Action | 更新日期: 2023-09-27 17:51:26

我正在重新组织我的单元测试,目前我正在寻找实现这一目标的不同可能性:

CustomerTests

[TestClass]
public class CustomerTests : SuperTestBaseClass {
    public CustomerTests() : base() { }
    [TestMethod]
    public void NameThrowsWhenNull() { 
        Throws<ArgumentNullException>(customer.Name = null);
    }
}

SuperTestBaseClass

public abstract class SuperTestBaseClass {
    protected SuperTestBaseClass() { }
    public void Throws<TException>(Func<T, TResult> propertyOrMethod) {
        // arrange
        Type expected = typeof(TException);
        Exception actual = null;
        // act
        try { propertyOrMethod(); } catch (Exception ex) { actual = ex; }
        // assert
        Assert.IsInstanceOfType(actual, expected);
    }
}

其中propertyOrMethod将在try/catch中执行,而不必写这样的东西:

try { propertyOrMethod.Name = null } catch...

因为目标是使这个方法尽可能的通用以促进代码重用。

可行吗?如果是,那么是怎么做的?

是否可以使用Func<T, result >或Action< T>为了达到这个目的

在你的方法上使用[ExpectedException(typeof(ArgumentNullException)],你将不需要任何自定义的东西。

[TestClass]
public class CustomerTests : SuperTestBaseClass {
    public CustomerTests() : base() { }
    [TestMethod]
    [ExpectedException(typeof(ArgumentNullException)]
    public void NameThrowsWhenNull() { 
        customer.Name = null;
    }
}

我会这样做:

public TException Throws<TException>(Action act) where TException : Exception 
{
        // act
        try { act(); } catch (TException ex) { return ex; }
        // assert
        Assert.Fail("Expected exception");
        return default(TException);   //never reached
}

然后你可以做

Throws<ArgumentNullException>(() => { customer.Name = null; });

请注意,NUnit内置了这个方法(Assert.Throws/Catch),所以如果你使用它,你不需要这个

如果你使用NUnit,那么你可以这样做:

Assert.That(() => { ... }, Throws.InstanceOf<ArgumentException>()));

如果需要,可以将lambda表达式替换为委托实例。

相关文章: