Search code examples
c#.netasync-awaitnunitgrpc

How to test a gRPC client in a parallel for with NUnit?


I would like to test when many users access to the server at the same time, so I am trying this code:

[Test]
public void Agregar2RegistrosHorariosDeEntradaDe2EmpleadosAsync()
{
    try
    {
        Parallel.For(0, 2,
                    async iterador =>
                    {
                        try
                        {
                            await miClienteLogin.LoginAsync(_nombreUsuario, _password);
                        }
                        catch(Exception ex)
                        {
                            throw;
                        }
                    });
    }
    catch(Exception ex)
    {
        Assert.Fail("No se debió producir ninguna excepción.");
    }
}

But I don't get any exception and the log in the server is this:

[13:38:29 DBG] Connection id "0HMPPMB4T" accepted.
[13:38:29 DBG] Connection id "0HMPPMB4T" started.
[13:38:29 DBG] Connection 0HMPPMB4T established using the following protocol: Tls13
[13:38:29 DBG] Connection id "0HMPPMB4T" reset.
[13:38:29 DBG] Connection id "0HMPPMB4T" is closed. The last processed stream ID was 0.
[13:38:29 DBG] The connection queue processing loop for 0HMPPMB4TUI6R completed.
[13:38:29 DBG] Connection id "0HMPPMB4T" sending FIN because: "The client closed the connection."
[13:38:29 DBG] Connection id "0HMPPMB4T" stopped.

But If I run the same code outside the parallel for, it works as expected.

I guess it has to be a problem when I execute the client command inside a parallel for.

How could I run it inside the parallel for? Or how could I test when many users are requesting something to the server?

Thanks.


Solution

  • Parallel.For is not task-aware so it will not actually wait for LoginAsync to finish before ending the loop (it will just start tasks and that's it). Use Parallel.ForEachAsync or just Task.WhenAll. Something like the following:

    [Test]
    public async Task Agregar2RegistrosHorariosDeEntradaDe2EmpleadosAsync()
    {
        try
        {
            await Task.WhenAll(Enumerable.Range(0, 2)
                .Select(_ => miClienteLogin.LoginAsync(_nombreUsuario, _password)));
        }
        catch (Exception ex)
        {
            Assert.Fail("No se debió producir ninguna excepción.");
        }
    }
    

    P.S.

    If you want to assert if something throws you can use Assert.Throws/Assert.ThrowsAsync.