es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo simular un delegado en xUnit

Tengo delegado esa llamada al método SendMessagesAsync, que toma un IEnumerable ProviderExemptionReceivedNotification. ¿Cómo simulo SendMessagesAsync que es el callBack del delegado? En otras palabras, ¿cómo hago un mock del Delegate?

Interfaz

public delegate Task SendAnprProviderExemptionNotifications(IEnumerable exemptions);

public interface IRingGoApiService
{
Task ProcessCreateRequestAsync(RingGoExemption ringGoExemption, SendAnprProviderExemptionNotifications sendProviderExemption);
}

Implementación del delegado

public async Task ProcessCreateRequestAsync(RingGoExemption ringGoExemption, SendAnprProviderExemptionNotifications sendProviderExemption)
{
var msgSent = await sendProviderExemption(new List() { exemption });
}

Clase de prueba

public MyTestClass{

public MyTestClass()
{
}

private readonly Mock providerExemptionServiceMoq;
}

Usando delegado

var result = await _ringGoApiService.ProcessCreateRequestAsync(ringGoExemption,
async (IEnumerable exemptions) => await SendMessagesAsync(servicebusMessage, exemptions)
);

SendMessagesAsync

static async Task SendMessagesAsync(IAsyncCollector collector, IEnumerable exemptions)
{
SetProviderExemption(exemptions);

var messages = exemptions.Select(exemption =>
{
    //Crear mensaje de ServiceBus...

    return message;
});

}

static void SetProviderExemption(IEnumerable exemptions)
{
providerExemption = exemptions.FirstOrDefault();
}

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para simular el delegado SendAnprProviderExemptionNotifications, puedes crear un Func que tome un parámetro IEnumerable<providerexemptionreceivednotification> y devuelva una Task<bool>. En tu prueba, puedes usar este Func en lugar de llamar al método real.

    Aquí tienes un ejemplo de cómo podrías actualizar tu clase de prueba para simular el delegado:

    public class MiClaseDePrueba
    {
        public MiClaseDePrueba()
        {
            providerExemptionServiceMoq = new Mock<iproviderexemptionservice>();
        }
    
        private readonly Mock<iproviderexemptionservice> providerExemptionServiceMoq;
    
        [Fact]
        public async Task MiMetodoDePrueba()
        {
            // Arrange
            var ringGoApiService = new RingGoApiService();
            var sendProviderExemptionMoq = new Func<><providerexemptionreceivednotification>, Task<bool>>(exenciones =>
            {
                // Simular el método SendMessagesAsync
                return Task.FromResult(true); // o cualquier resultado deseado
            });
    
            // Simular el método ProcessCreateRequestAsync y pasar la simulación del delegado
            providerExemptionServiceMoq
                .Setup(x => x.ProcessCreateRequestAsync(It.IsAny<ringgoexemption>(), It.IsAny<sendanprproviderexemptionnotifications>()))
                .ReturnsAsync(new RingGoMessageResponseResult()); // o cualquier resultado deseado
            var ringGoApiServiceMock = providerExemptionServiceMoq.Object;
    
            // Act
            await ringGoApiServiceMock.ProcessCreateRequestAsync(new RingGoExemption(), sendProviderExemptionMoq);
    
            // Assert
            // realizar las aserciones necesarias
        }
    }
    

    En este ejemplo, la variable sendProviderExemptionMoq contiene un Func configurado para simular el método SendMessagesAsync y devolver un resultado deseado. Luego, se llama al método ProcessCreateRequestAsync con la simulación del delegado como parámetro. Por último, se pueden realizar las aserciones necesarias basadas en los resultados.

Comments are closed.