【问题标题】:Convert a function with 2 parameters into a lambda action将具有 2 个参数的函数转换为 lambda 动作
【发布时间】:2017-02-13 19:46:46
【问题描述】:

我想测试(使用using Microsoft.VisualStudio.TestTools.UnitTesting)这个测试函数的第一行会导致DataMisalignedException 被抛出。

namespace xxx.Services.SupplierApiTests
{
    [TestClass]
    public class JsonSchemaValidatorTests
    {
        [TestMethod]
        public void ShouldThrowOnBadPhoneNumber()
        {
            JsonSchemaValidator.validateAgainstJsonSchema(ProviderService.getErronousProviders(), "./provider-schema.json");
            Action<IList, string> myAction = (x, y) => JsonSchemaValidator.validateAgainstJsonSchema(x, y);
            Assert.ThrowsException<DataMisalignedException>(myAction);
        }
    }
}

我如何使用JsonSchemaValidator.validateAgainstJsonSchema 作为一个动作,从测试的第一行传入两个参数?我的尝试是在上面的代码中,但没有传递两个参数。

【问题讨论】:

  • 我想你想要Assert.ThrowsException&lt;DataMisalignedException&gt;(() =&gt; JsonSchemaValidator.validateAgainstJsonSchema(ProviderService.getErronousProviders(), "./provider-schema.json")),但我找不到Assert.ThrowsException 的文档我自己通常只在测试方法上使用ExpectedException 属性。
  • @juharr 是的,谢谢,这就是我想要的。我看到它没有转换函数,而是在匿名函数中调用它。干杯
  • 我的猜测是 Assert.ThrowsException 需要 Action 而不是 Action&lt;IList, string&gt;
  • ThrowsException() 也可能希望将参数列表传递给操作。但我在 MSDN 中找不到该方法的参考...

标签: c# lambda action assert


【解决方案1】:

要表明在测试方法执行期间预期会出现异常,您可以使用测试方法顶部的[ExpectedException] 属性。

[TestClass]
public class JsonSchemaValidatorTests
{
    [TestMethod]
    [ExpectedException(typeof(DataMisalignedException))]
    public void ShouldThrowOnBadPhoneNumber()
    {
        JsonSchemaValidator.validateAgainstJsonSchema(ProviderService.getErronousProviders(), "./provider-schema.json");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 2011-11-12
    • 2018-01-15
    相关资源
    最近更新 更多