c# moq 测试异步任务

c# moq test async task

我正在尝试使用 Moq 来测试一些异步任务,但没有成功。

我可以制作模拟的东西,但是当我尝试使用 mock.Object 它抛出(对象 = 'm.Object' 抛出类型 'Castle.DynamicProxy.Generators.GeneratorException' 的异常)并且 VS 停止到 debug/run.

这里是测试的Moq方式:

interface ITestAsync
        {
            Task<IEnumerable<string>> get();
        }

        [Fact]
        public async Task MoqShouldReturnFIRST()
        {
            var m = new Mock<ITestAsync>();
            m.Setup(q => q.get()).ReturnsAsync(null);

            var x = await m.Object.get().FirstIfNotNullOrEmptyAsync();

            x.Should().BeNull();
        }

这里是使用 xUnit 的传统方式的测试

public class FirstIfNotNullOrEmptyAsyncTests
    {

        private async Task<IEnumerable<string>> getAll()
        {
            List<string> x = new List<string>();
            x.Add("01");
            x.Add("02");

            await Task.Delay(1000);

            return x;
        }

        private async Task<IEnumerable<string>> getNull()
        {
            List<string> x = new List<string>();
            x = null;

            await Task.Delay(1000);

            return x;
        }

        private async Task<IEnumerable<string>> getEmpty()
        {
            List<string> x = new List<string>();

            await Task.Delay(1000);

            return x;
        }

        [Fact]
        public async Task ShouldReturnFIRST()
        {
            var x = await getAll().FirstIfNotNullOrEmptyAsync();

            x.Should().Be("01");
        }

        [Fact]
        public async Task ShouldReturnNULLforNULL()
        {
            var x = await getNull().FirstIfNotNullOrEmptyAsync();

            x.Should().BeNull();
        }

        [Fact]
        public async Task ShouldReturnNULLforEMPTY()
        {
            var x = await getEmpty().FirstIfNotNullOrEmptyAsync();

            x.Should().BeNull();
        }
    }

我要测试的扩展是:

public static async Task<T> FirstIfNotNullOrEmptyAsync<T>(this Task<IEnumerable<T>> obj) where T : class
        {
            var result = await obj;

            return (result != null && result.Any()) ? result?.FirstOrDefault() : null;
        }

唯一的初始问题是接口是私有的(但猜测这是由于示例最少)。

出现以下错误

Castle.DynamicProxy.Generators.GeneratorException: Can not create proxy for type Moq.IMocked`1[[****+ITestAsync, *****, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because type ****+ITestAsync is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(InternalsVisible.ToDynamicProxyGenAssembly2)] attribute, because assembly Moq is strong-named.

界面制作完成后public一切worked/passed

public interface ITestAsync {
    Task<IEnumerable<string>> get();
}