我正在编写一个小包装器( MyWrapper
)用于单元测试。其目的是用 try-catch 包装测试代码,以捕获一个特定异常 ( MySpecialException
),然后忽略测试。
为什么我这样做应该与这个问题无关。
鉴于下面的代码,我如何防止其他人传递 Action
并像这样使用异步?
或者换句话说:我如何强制他们使用 MyWrapper.ExecuteAsync(Func<Task>)
相反?
using System;
using System.Threading.Tasks;
using NUnit.Framework;
namespace PreventAsyncActionLambdaExample
{
[TestFixture]
public class Example
{
[Test]
public async Task ExampleTest()
{
// How do I prevent others from passing an action and using async like this?
// Or in other words: How do I force them to use MyWrapper.ExecuteAsync(Func<Task>) instead?
MyWrapper.Execute(async () =>
{
var cut = new ClassUnderTest();
await cut.DoSomethingAsync();
Assert.Fail("Problem: This line will never be reached");
});
}
}
public static class MyWrapper
{
// This method SHOULD NOT, BUT WILL be used in this example
public static void Execute(Action action)
{
try
{
action();
}
catch (MySpecialException)
{
Assert.Ignore("Ignored due to MySpecialException");
}
}
// This method SHOULD BE USED in this example, BUT WILL NOT be used.
public static async Task ExecuteAsync(Func<Task> func)
{
try
{
await func();
}
catch (MySpecialException)
{
Assert.Ignore("Ignored due to MySpecialException");
}
}
}
public class MySpecialException : Exception
{
// This is another exception in reality which is not relevant for this example
}
public class ClassUnderTest
{
public Task DoSomethingAsync()
{
return Task.Delay(20); // Simulate some work
}
}
}
最佳答案
恐怕您无法在编译时真正阻止这种情况,但您可以编写另一个重载,在这种情况下将拾取该重载,以告诉他们应该使用ExecuteAsync
相反:
public static Task Execute(Func<Task> action)
{
throw new Exception("Please use the ExecuteAsync(Func<Task> func) method instead if you will be passing async lambdas");
}
关于c# - 如何防止操作参数成为异步 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588195/