Search code examples
c#unit-testingethereum

Nethereum C# Unit Test GetTransactionCount


Nethereum uses an Async method to get the TransactionCount of an address.

I have put the method into a async task:

public  async Task<object>  GetTxCount(string address)
{
  return await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(address).ConfigureAwait(false);
}

And attempting to test it with...

[TestMethod]
public async Task TestMethodAsync()
{
  string address = "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae";
  EthTest.Eth et = new EthTest.Eth();
  var encoded = et.GetTxCount(address);
  encoded.Wait();     
}

How should I call the GetTxCount from a unit test to get the actual result.

I have used the "wait" command even though it is not recommended, but still cannot get it to return a result.

The Unit test bombs out - it does not even hit the API that Nethereum calls.


Solution

  • You have already made the test async then use async all the way through by using await to call GetTxCount

    [TestMethod]
    public async Task TestMethodAsync() {
        string address = "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae";
        var et = new EthTest.Eth();
        var encoded = await et.GetTxCount(address);
    }
    

    Given that GetTxCount is just returning the task then there really is no need to await it in the method.

    Refactor to

    public Task<HexBigInteger>  GetTxCount(string address) {
        return  web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(address);
    }
    

    or

    public async Task<HexBigInteger>  GetTxCount(string address) {
        var result = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(address).ConfigureAwait(false);
        return result.
    }
    

    Reference Async/Await - Best Practices in Asynchronous Programming