none
WebServices with Windows-authentication C# RRS feed

  • Question

  • Hello,
           
    It is a bit clearer, as you meant it.
    What should I enter there, what does the format look like?    Please search // **** not clear!
    Do you have an example for me? 
    I can test one function, not the whole process.

    With best regards Markus

    MainApp using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace WebClient { class Program { static void Main(string[] args) { } } public class AssemblyNumber { //is int public int Begin { get; set; } public string Charge { get; set; } //is int public int Current { get; set; } public int EndNumber { get; set; } public string Error { get; set; } } public class AssemblyNumberHttpClient : HttpClient { public AssemblyNumberHttpClient(string baseUrl) { _baseUrl = baseUrl.TrimEnd('/'); } public async Task<AssemblyNumber> GetAssemblyNumberAsync(string orderId, int assemblyId) { //In general a client should wrap the resource URL and only require the base URL from the caller //This URL looks like more than a resource URL but it isn't clear where the split would occur var url = BuildUrl($"NumberService/GetNewNumbers/masterLoc/Group/workOrder/{orderId}/Test/assemblyNumber/{assemblyId}"); //Changing this to a virtual call so it can be mocked var response = await MakeGetAsync(url); response.EnsureSuccessStatusCode(); //Get formatted data //This uses an extension method to cut down on the code so you need //to add the Microsoft.AspNet.WebApi.Client package from NuGet to get it return await response.Content.ReadAsAsync<AssemblyNumber>(); } protected virtual Task<HttpResponseMessage> MakeGetAsync(string url) { return GetAsync(url); } //Simple URL builder private string BuildUrl(string resource) { //Combine with base URL return _baseUrl + "/" + resource.TrimStart('/'); } private readonly string _baseUrl; } } Test Class using Microsoft.VisualStudio.TestTools.UnitTesting; using WebClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using System.Net; namespace WebClient.Tests { [TestClass()] public class AssemblyNumberHttpClientTests { [TestMethod()] public void GetAssemblyNumberAsyncTest() { } [TestMethod] public async Task GetValidResponse() { var target = new MyTestClient(); // **** not clear! // ** As string , is not working

    target.GetResponse = url => "{\t\"}}"; // /* Put a valid JSON string response here */; //Run the test var actual = await target.GetAssemblyNumberAsync("abc", 123); //Verify the actual value matches the JSON you sent } [TestMethod] public async Task GetWith404() { // What happens when we get a 404 error? var target = new MyTestClient(); target.GetResponse = url => new HttpResponseMessage(HttpStatusCode.NotFound); //Run the test - will probably throw an exception //that you'll need to handle... var actual = await target.GetAssemblyNumberAsync("abc", 123); } private sealed class MyTestClient : AssemblyNumberHttpClient { public MyTestClient() : base("http://www.google.com") { } public delegate HttpResponseMessage GetResponseDelegate(string url); //Helper method to define what gets "returned" from //the client public GetResponseDelegate GetResponse { get; set; } protected override Task<HttpResponseMessage> MakeGetAsync(string url) { return Task.FromResult(GetResponse(url)); } } } }


        
    Friday, January 26, 2018 5:11 PM

Answers

  • https://www.telerik.com/products/mocking/unit-testing.aspx

    <copied>

    Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to focus on the code being tested and not on the behavior or state of external dependencies.

    <end>

    Of course, your external dependency is the Web service that needs to be mocked out.

    https://www.codeproject.com/Tips/743246/How-to-Mock-Visual-Studio-Generated-Web-Services-U

    https://deanhume.com/home/blogpost/basic-introduction-to-writing-unit-tests-with-moq/16

    <copied>

    _mock.Setup(x => x.GetCustomerTotal(It.IsAny<int>())).Returns(25.5);

    <end>

    The key for you here is this.

    The call to the Web service must be using internal method that returns the result, which could be the response, a siring,  an object ect, ect. in your code, doing this for real - no test applied to it do it for real in your code.

    The method is a real method in your code's functionality to call the Web service.

    You mockout the real method that is going to call the Web service and you mock the return like you see it on the mock above.

    //arrange

    string response = "test"

    mock.Setup(x => x.GetCustomerTotal()).Returns(response);

     //act

    //run the real method you are trying to unit test that is mocked out

    var result = GetCustomer();

    //assert

    Assert.IsEqual(result, "test");

    You have articles and some pseudo code explaining what is need to test the Web service  verifying that the method ran, it retuned the result that you arranged and passed into the method executing the code path but not actually making the call to the Web service and verifying the expected retuned result at the assert.

    Arrange, Act, Assert

    http://defragdev.com/blog/?p=783

    The forum is where you should post for further help.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vsunittest

     

     

    • Marked as answer by Markus Freitag Wednesday, January 31, 2018 4:53 PM
    Tuesday, January 30, 2018 8:47 PM

All replies

  • Friday, January 26, 2018 5:24 PM
  • @CoolDadTx,
      Can you please answer me / help me.

    How can I generate a test message?
    Could you please give me an example?
    Please look there ######## not working ########
    Thanks in advance.   ok, maybe another Forum is right, but I think the experts also here.
    With best regards Markus
    namespace WebClient.Tests
    {
        [TestClass()]
        public class AssemblyNumberHttpClientTests
        {
            [TestMethod()]
            public void GetAssemblyNumberAsyncTest()
            {
            }
            //public int Begin { get; set; }
            //public string Charge { get; set; }
            ////is int
            //public int Current { get; set; }
            //public int EndNumber { get; set; }
            //public string Error { get; set; }
            public HttpResponseMessage DelegateMethodGetResponse(string url)
            {
                string retTest = "{  \"Begin\": \"1001\",   \"Current\": \"1002\",  \"EndNumber\": \"1099\",   \"Error\": \"\",   \"Charge\": \"0M-13339742\" }";
                HttpResponseMessage obj = new HttpResponseMessage(HttpStatusCode.OK);
                return obj;
            }
            private HttpResponseMessage CreateResponse(HttpStatusCode badRequest, string v)
            {
                throw new NotImplementedException();
            }
            public string DelegateMethodGetResponseWithString(string url)
            {
                string retTest = "{  \"Begin\": \"1001\",   \"Current\": \"1002\",  \"EndNumber\": \"1099\",   \"Error\": \"\",   \"Charge\": \"0M-13339742\" }";
                return retTest;
            }
            [TestMethod]
            public async Task GetValidResponse()
            {
                var target = new MyTestClient();
                string retTest = "{  \"Begin\": \"1001\",   \"Current\": \"1002\",  \"EndNumber\": \"1099\",   \"Error\": \"\",   \"Charge\": \"0M-13339742\" }";
                //System.Net.Http.CreateResponse<string>
                //target.GetResponse = url => (HttpResponseMessage)"rrrrr";
                //target.GetResponse = url => { return retTest };  ######## not working ########
                target.GetResponse = DelegateMethodGetResponse;
                target.GetResponse(retTest);
                //target.GetResponse 
                //target.GetResponse = DelegateMethodGetResponse;
                target.GetResponseWithString = url => "TESTTTTTTT";
                target.GetResponseWithString = DelegateMethodGetResponseWithString;
                target.GetResponseWithString("Hallo");
    
                //Run the test
                var actual = await target.GetAssemblyNumberAsync("abc", 123);
                //Verify the actual value matches the JSON you sent
            }
            [TestMethod]
            public async Task GetWith404()
            {
                // What happens when we get a 404 error?
                var target = new MyTestClient();
                target.GetResponse = url => new HttpResponseMessage(HttpStatusCode.NotFound);
                //Run the test - will probably throw an exception
                //that you'll need to handle...
                var actual = await target.GetAssemblyNumberAsync("abc", 123);
            }
            private sealed class MyTestClient : AssemblyNumberHttpClient
            {
                public MyTestClient() : base("http://www.google.com")
                {
                }
                public delegate HttpResponseMessage GetResponseDelegate(string url);
                //Helper method to define what gets "returned" from
                //the client
                public GetResponseDelegate GetResponse { get; set; }
    
                public delegate string GetResponseDelegateWithString(string url);
                public GetResponseDelegateWithString GetResponseWithString { get; set; }
    
                protected override Task<HttpResponseMessage> MakeGetAsync(string url)
                {
                    return Task.FromResult(GetResponse(url));
                }
            }
        }
    }
    Monday, January 29, 2018 5:36 PM
  • How can I generate a test message?
    Could you please give me an example?

    What are you trying to do here a unit or integration test, based on unit test rules?

    http://www.artima.com/weblogs/viewpost.jsp?thread=126923

    If you were doing an unit test, then you would have mocked out any call to the Web service and retuned a mocked response.

    Monday, January 29, 2018 7:50 PM
  • Hello,

    HttpResponseMessage obj = new HttpResponseMessage(HttpStatusCode.OK);

    For my test project I would like to return a dummy string. The question is simple, is that possible? If yes how?
    // simulate my own answer?
    var target = new MyTestClient();
    target.GetResponse = url => new HttpResponseMessage(HttpStatusCode.NotFound);
    public delegate HttpResponseMessage GetResponseDelegate(string url);
    public GetResponseDelegate GetResponse { get; set; }
    public delegate string GetResponseDelegateWithString(string url);
    public GetResponseDelegateWithString GetResponseWithString { get; set; }


    I need a type of HttpResponseMessage.
    With best regards Markus


    Tuesday, January 30, 2018 5:41 PM
  • https://www.telerik.com/products/mocking/unit-testing.aspx

    <copied>

    Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to focus on the code being tested and not on the behavior or state of external dependencies.

    <end>

    Of course, your external dependency is the Web service that needs to be mocked out.

    https://www.codeproject.com/Tips/743246/How-to-Mock-Visual-Studio-Generated-Web-Services-U

    https://deanhume.com/home/blogpost/basic-introduction-to-writing-unit-tests-with-moq/16

    <copied>

    _mock.Setup(x => x.GetCustomerTotal(It.IsAny<int>())).Returns(25.5);

    <end>

    The key for you here is this.

    The call to the Web service must be using internal method that returns the result, which could be the response, a siring,  an object ect, ect. in your code, doing this for real - no test applied to it do it for real in your code.

    The method is a real method in your code's functionality to call the Web service.

    You mockout the real method that is going to call the Web service and you mock the return like you see it on the mock above.

    //arrange

    string response = "test"

    mock.Setup(x => x.GetCustomerTotal()).Returns(response);

     //act

    //run the real method you are trying to unit test that is mocked out

    var result = GetCustomer();

    //assert

    Assert.IsEqual(result, "test");

    You have articles and some pseudo code explaining what is need to test the Web service  verifying that the method ran, it retuned the result that you arranged and passed into the method executing the code path but not actually making the call to the Web service and verifying the expected retuned result at the assert.

    Arrange, Act, Assert

    http://defragdev.com/blog/?p=783

    The forum is where you should post for further help.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vsunittest

     

     

    • Marked as answer by Markus Freitag Wednesday, January 31, 2018 4:53 PM
    Tuesday, January 30, 2018 8:47 PM
  • The forum is where you should post for further help.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vsunittest

     

     

    ok. It is really not easy. I will see it.

    The question is simple, is that possible? If yes how?
    // simulate my own answer? From type HttpResponseMessage

    Regards Markus

    Wednesday, January 31, 2018 4:53 PM