0

I am trying to get an integration test to work on the project but the same error keeps showing up. Doing the same thing manually with postman works fine.

I have tried changing the port number and turning on/off SSL but still the same issue appears.

UserAPITest :

[TestClass]
    public class UserAPITest
    {
        private readonly HttpClient _client;
        private readonly IConfiguration _configuration;

        public UserAPITest()
        {
            _client = TestsHelper.Client;
            _configuration = TestsHelper.Configurations;
        }

        [TestInitialize]
        public void TestInitialize()
        {
        }

        [TestMethod]
        [DataRow(nameof(HttpMethod.Post), "api/User/refreshToken")]
        public async Task Initiation_Authorized_ShouldReturnNewToken(string httpMethod, string url)
        {
            _client.DefaultRequestHeaders.Authorization = TestsHelper.GetTestUserBearerHeader();
            var request = new HttpRequestMessage(new HttpMethod(httpMethod), url);

            var response = await _client.SendAsync(request);

            Assert.IsNotNull(response.Content); // value during debug added below

            Assert.AreEqual(HttpStatusCode.OK,response.StatusCode); // test fails here

// check for token inside response
            // Assert.IsTrue(Regex.IsMatch(response.RequestMessage.Content.ToString(), "^[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.?[A-Za-z0-9-_.+/=]*$"));
        }
    }

TestsHelper:


        private static HttpClient SetClient()
        {
            HttpClient client;
            var host = new WebHostBuilder()
                                    .UseEnvironment("Development")
                                    .UseStartup<Startup>()
                                    ;

            var server = new TestServer(host);

            client = new HttpClient {BaseAddress = new Uri(Configurations["Tests:ApiClientUrl"], UriKind.RelativeOrAbsolute)};

            return client;
        }

        public static string GetTestUserToken()
        {
            var token = "someToken"; // there is an actual token here but I have removed it

            return token;
        }
        public static AuthenticationHeaderValue GetTestUserBearerHeader()
        {
            var token = GetTestUserToken();
            var bearerToken = new AuthenticationHeaderValue("Bearer", token);

            return bearerToken;
        }

Expected Result: test either passing (returns token) or failing (returns 401 unauthorized)

Actual Result: test returns 301 source has been moved

value of response:

{StatusCode: 301, ReasonPhrase: 'Moved Permanently', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
  Cache-Control: no-cache
  Pragma: no-cache
  Proxy-Connection: close
  Connection: close
  Content-Type: text/html; charset=utf-8
  Content-Length: 668
}}

2 Answers 2

1

you need to modify your test case to

_client.DefaultRequestHeaders.Authorization = TestsHelper.GetTestUserBearerHeader();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), url);

var response = await _client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();

Assert.IsNotNull(content);

Assert.AreEqual(HttpStatusCode.OK,response.StatusCode);

Update Problem was on both TestServer and in Client

var server = new TestServer(Program.CreateWebHostBuilder(new string[] { }));
client = server.CreateClient();
client.BaseAddress = new Uri(Configurations["Tests:ApiClientUrl"]);
Sign up to request clarification or add additional context in comments.

4 Comments

I gave it a shot, sadly it didn't work. Thanks for trying
Sounds dumb, but can you change "api/User/refreshToken" into "/api/User/refreshToken"?
From what I know if you didn't add '/' in the beginning, it will be handled in HttpRequestMessage. But for the sake of trying I did and nothing changed.
I see, one more suggestion, I have a feeling that webHostBuild or client is incorrect configured, last suggestion, replace initialization with this: server = new TestServer(Program.CreateWebHostBuilder(new string[] {})); client = server.CreateClient();
0

when constructing test http client use this: server.CreateClient() instead of client = new HttpClient {BaseAddress = new Uri(Configurations["Tests:ApiClientUrl"], UriKind.RelativeOrAbsolute)};

The youre doing is not working, because the test server you are constructing actually does not expose endpoints at http level. You use the test server and test client to test your webapi/http integration while the test infra short circuits the entire http protocol stack in memory.

https://andrewchaa.me.uk/programming/2019/03/01/unit-testing-with-ASP-NET-Core.html

1 Comment

this threw an error the constraint reference 'langCon' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.Route Options.Constraint Map'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.