C
Craig Muckleston (MCPD, MCTS)
Guest
I am trying to write some unit tests (Nunit) for the class below.
public async Task<IEnumerable<T>> GetAll<T>(string url)
{
IEnumerable<T> result = new List<T>();
try
{
var response = httpClient.GetAsync(new Uri(url)).Result;
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<IEnumerable<T>>(x.Result);
});
}
catch (Exception ex)
{
throw ex;
}
return result;
}
And a unit test looks like this:
private Mock<HttpClientService> httpClientServiceMock;
/// <summary>
/// Called just before each test
/// </summary>
[SetUp]
public void Setup()
{
httpClientServiceMock = new Mock<HttpClientService>() { CallBase = true };
}
/// <summary>
/// Called after each test
/// </summary>
[TearDown]
public void TearDown()
{
httpClientServiceMock = null;
}
[Test]
[TestCase("nonemptystring")]
public async Task GetAll_ReturnType_Is_IEnumerable<T>(string url)
{
// Arrange
// Act
var actualResult = await httpClientServiceMock.Object.GetAll<T>(url).ConfigureAwait(false);
// Assert
Assert.IsInstanceOf(typeof(IEnumerable<T>), actualResult);
}
However, I get an error 'Unable to determine type arguments for method'
Continue reading...
public async Task<IEnumerable<T>> GetAll<T>(string url)
{
IEnumerable<T> result = new List<T>();
try
{
var response = httpClient.GetAsync(new Uri(url)).Result;
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<IEnumerable<T>>(x.Result);
});
}
catch (Exception ex)
{
throw ex;
}
return result;
}
And a unit test looks like this:
private Mock<HttpClientService> httpClientServiceMock;
/// <summary>
/// Called just before each test
/// </summary>
[SetUp]
public void Setup()
{
httpClientServiceMock = new Mock<HttpClientService>() { CallBase = true };
}
/// <summary>
/// Called after each test
/// </summary>
[TearDown]
public void TearDown()
{
httpClientServiceMock = null;
}
[Test]
[TestCase("nonemptystring")]
public async Task GetAll_ReturnType_Is_IEnumerable<T>(string url)
{
// Arrange
// Act
var actualResult = await httpClientServiceMock.Object.GetAll<T>(url).ConfigureAwait(false);
// Assert
Assert.IsInstanceOf(typeof(IEnumerable<T>), actualResult);
}
However, I get an error 'Unable to determine type arguments for method'
Continue reading...