Azure / autorest.csharp

Extension for AutoRest (https://github.com/Azure/autorest) that generates C# code
MIT License
141 stars 166 forks source link

How to use an autorest generated c# client with TestHost? #156

Open piccaso opened 6 years ago

piccaso commented 6 years ago

I'm trying to find out how to do integration tests, here is my approach:

        [SetUp]
        public void SetUp() {
            var host = new WebHostBuilder().UseStartup<Startup>();
            var server = new TestServer(host);
            var messageHandler = server.CreateHandler() as HttpClientHandler;
            _apiClient = new MyAPI(messageHandler);
            _httpClient = server.CreateClient();
        }

        [Test]
        public void AutoRest() {
            var value = _apiClient.ApiValuesGet(); // throws: Microsoft.Rest.HttpOperationException : Operation returned an invalid status code 'NotFound'
            TestContext.WriteLine(string.Join(",", value));
        }

        [Test] // works fine here...
        public async Task HttpClient() {
            var values = await _httpClient.GetStringAsync("/api/Values");
            TestContext.WriteLine(values);
            Assert.IsTrue(values.Contains("value1"));
        }

the whole file is here.
but that ist probably not the right way to setup an autorest client with a testhost...
Is there any documentation on this or an example?

piccaso commented 6 years ago

I found a way to make it work (at least it seems that way for now).
By using reflection to change the HttpClient - which does not feel like a good idea :)

public void SetUp() {
    var host = new WebHostBuilder().UseStartup<Startup>();
    var server = new TestServer(host);

    _httpClient = server.CreateClient();
    _apiClient = new MyAPI();
    _apiClient.GetType()
        .GetProperty(nameof(_apiClient.HttpClient))
        .SetValue(_apiClient, _httpClient);
}