2Fast4YouBR 2Fast4YouBR - 23 days ago 25
C# Question

c# moq test async task

I am trying to use Moq for test some Async Task stuff with no sucess.

I could make the the mock stuff, but when I try to use mock.Object it throws (Object = 'm.Object' threw an exception of type 'Castle.DynamicProxy.Generators.GeneratorException') and VS stops to debug/run.

Here id the Moq way of the test:

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();
}


Here is the test in the traditional way using 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();
}
}


My Extention that I am trying to test is:

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;
}

Answer

Only initial issue was that the interface was private (but guessed that was due to minimal example).

Got the following error

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.

Once interface was made public everything worked/passed

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