-1

I have to write automated test scripts for an API by sending a request and validating the response and I don't know where to begin. The API Client is pretty simple and apparently from the developers all I need from the code is this which is the APIClient:

using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using API.Models;

namespace AutomatedAPI
{

    public interface ApiClient
    {
        Task AuthenticateAsync(string clientId, string clientSecret);
        void SetBearerToken(string token);
        Task<ApiResponse<PagedItemResult>> SearchIemsAsync(int? page = 1, Guid? shopId = null);
    }
}

This is all housed in VS, so I have created my own API test class and tried the following:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using API;


namespace API.Automation
{
    [TestClass]
    public class SearchItems
    {
        private Uri apiBaseUri => new Uri("https://qa-shop-items.azurewebsites.net");
        private Uri identityBaseUri => new Uri("https://qa-shop-store");
        [TestMethod]
        public async Task TestMethod()
        {
            var itemId = new Guid("fsdf78dsff-fsdgfg89g-fsgvssfdg89");
            var client = new ThirdPartyApiClient(apiBaseUri);
            client.SetBearerToken("Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkI4QzE2QUNEOEYxODR");
            ApiResponse<Item> result = await client.GetItemAsync(itemId);
        }
    }
}

Now no errors in the syntax but when I run my script I get the following message:

Message: 
    Test method API.Automation.SearchItemss.TestMethod threw exception: 
    System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
  Stack Trace: 
    ApiClient.deserializeTokenPart[T](String tokenPart)
    ApiClient.SetBearerToken(String token) line 98
    <TestMethod>d__4.MoveNext() line 20
    --- End of stack trace from previous location where exception was thrown ---
    TaskAwaiter.ThrowForNonSuccess(Task task)
    TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    ThreadOperations.ExecuteWithAbortSafety(Action action)

As I have not used Task before can someone tell me how to implement this SearchItems method? Or at least give me a template of how this is done?

  • 1
    Make the test method `async` an use `await` before `client.GetFleetAsync(itemId);`, like in this thread [How does one test async code using MSTest](https://stackoverflow.com/questions/2060692/how-does-one-test-async-code-using-mstest) – Pavel Anikhouski Jan 06 '20 at 20:35

2 Answers2

-1

You need to invoke GetItemAsync() with 'await'. Your code becomes:

ApiResponse<Items> x = await client.GetItemAsync(itemId);

Also, a method that uses await calls must be declared as 'async Task'. So your test method signature becomes:

public async Task TestMethod()
{
    ...
}

You can check for actual exception(suggested test method):

public async Task TestMethod()
{
    var itemId = new Guid("fsdf78dsff-fsdgfg89g-fsgvssfdg89"); 
    var client = new ThirdPartyApiClient(apiBaseUri);
    client.SetBearerToken("Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkI4QzE2QUNEOEYxODR"); 
    try
    {
        ApiResponse<Item> result = await client.GetItemAsync(itemId);

        // Get response data as string
        if( result.IsSuccessStatusCode )
        {
            var stringResponse = await result.Content.ReadAsStringAsync();
        }
    }
    catch(HttpRequestException ex)
    {
        var innerEx = ex.InnerException;
        if( innerEx != null && innerEx is WebException )
        {
            // Check status value
            var webEx = innerEx as WebException;
            var webExStatus = webEx.Status;
            if( webExStatus ==  WebExceptionStatus.NameResolutionFailure )
            {
                // This indicates a DNS resolution issue. You may need to use a proxy or fix the connection issue at this point.
                Assert.Fail("DNS Resolution failed");
            }
        }
    }
}
the-petrolhead
  • 597
  • 1
  • 5
  • 16
  • Used your suggestions guide and there are no syntax problems but when I run the test method see error above? – Chris Shenko Jan 06 '20 at 21:18
  • Mostly the reason for the error could be the conflicting dependency versions for 'Newtonsoft.Json'. Check the version in your project dependencies. Even if your project does not reference it, other dependencies should ideally reference the same version. If they don't, you may need to update those dependencies. See the related GitHub issue: https://github.com/aws/aws-lambda-dotnet/issues/453 – the-petrolhead Jan 06 '20 at 21:30
  • Added using Newtonsoft.Json; and get this message now: Test method API.Automation.SearchItems.TestMethod threw exception: System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The remote name could not be resolved: 'qa-shop-items.azurewebsites.net' – Chris Shenko Jan 06 '20 at 21:33
  • Seems to be network connectivity or DNS issue. Check this out: https://stackoverflow.com/questions/25014110/system-net-webexception-the-remote-name-could-not-be-resolved – the-petrolhead Jan 06 '20 at 21:38
  • Should I put the code in the test method? – Chris Shenko Jan 06 '20 at 21:40
  • For debugging, you should put the try/catch in the test. Once you know and fix the actual issue, you can remove the code and expect the test to pass. – the-petrolhead Jan 06 '20 at 21:44
  • Hmmmmm, as a newbie petrolhead, could you be so kind and create a code piece for my method with the try and catch, not sure if I should create my own try/catch or use existing...bit confused : ( – Chris Shenko Jan 06 '20 at 21:55
  • @the-petrolhead....thanks for your help buddy!! : ) – Chris Shenko Jan 06 '20 at 21:59
  • Updated answer with suggested test code. – the-petrolhead Jan 06 '20 at 22:23
  • it passed so no DNS issues? – Chris Shenko Jan 06 '20 at 22:33
  • Ah, the apiBaseUri was wrong.....so sorry!!! – Chris Shenko Jan 06 '20 at 22:42
  • Why don't I get any data from the result response? – Chris Shenko Jan 06 '20 at 22:49
  • @ChrisShenko Updated answer to show how to get response data as string. – the-petrolhead Jan 07 '20 at 03:48
-1

I added a line to fail the test when DNS fails. Please check if this fails your test. Else, debug through the code and check the value of WebException.Status.

the-petrolhead
  • 597
  • 1
  • 5
  • 16