0

I am using Xunit and AutoFixture. Here is my service which is calling third party service.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
    public class NPIDataService : INPIDataService
    {

        /// <summary>
        /// Gets the collection of NPI records matched to criteria
        /// </summary>
        public List<NPIRecord> GetData(string npiCode, string entityType, string firstName, string name, string address1, string address2, string state, string city, string zip,int pageNumber,int pageSize)
        {
            using (new LogActivity("GetNPIData"))
            {

                try
                {
                    ParameterValidator.ValidateEntityParameter(entityType);
                    ParameterValidator.ValidatePageNoAndSize(pageNumber, pageSize);
                    var npiRecords = new List<NPIRecord>();
                    var qfparam = string.Empty;
                    if (!string.IsNullOrEmpty(npiCode) && npiCode != "null")
                    {
                        qfparam = "NPI:true:" + npiCode;
                    }
                    else
                    {
                        if (entityType == "1")
                        {
                            if (name != null && name != "null")
                                qfparam = "LastName:false:" + name;

                            if (firstName != null && firstName != "null")
                                qfparam = qfparam + "&qf=FirstName:false:" + firstName;
                        }
                        else
                        {
                            if (name != null && name != "null")
                                qfparam = "&qf=OrganizationName:false:" + name;
                        }

                        if (!string.IsNullOrEmpty(address1) && address1 != "null")
                            qfparam = qfparam + "&qf=Address1:false:" + address1;

                        if (!string.IsNullOrEmpty(address2) && address2 != "null")
                            qfparam = qfparam + "&qf=Address2:false:" + address2;

                        if (!string.IsNullOrEmpty(state) && state != "null")
                            qfparam = qfparam + "&qf=State:false:" + state;

                        if (!string.IsNullOrEmpty(city) && city != "null")
                            qfparam = qfparam + "&qf=City:false:" + city;

                        if (!string.IsNullOrEmpty(zip) && zip != "null")
                            qfparam = qfparam + "&qf=Zip:false:" + zip;
                     }

                    var hippaBaseUrl = "http://www.HIPAASpace.com/api/npi/paginate_with_predicates";

                    var parameterQuery = string.Format("?&qf={0}&pageNo={1}&pageSize={2}&rt=xml&token=3932f3b0-cfab-11dc-95ff-0800200c9a663932f3b0-cfab-11dc-95ff-0800200c9a66", qfparam, pageNumber, pageSize);

                    var request = (HttpWebRequest)WebRequest.Create(hippaBaseUrl + parameterQuery);
                    int numberOfRetreis = 0;
                    while (numberOfRetreis < 5)
                    {
                        numberOfRetreis++;
                        HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
                        if (resp != null && resp.StatusCode == HttpStatusCode.OK)
                        {
                            MemoryStream responseMemStream = new MemoryStream();
                            int nRead;
                            byte[] buf = new byte[4096];
                            while ((nRead = resp.GetResponseStream().Read(buf, 0, 4096)) > 0)
                            {
                                responseMemStream.Write(buf, 0, nRead);
                            }

                            MemoryStream ms = new MemoryStream(responseMemStream.ToArray());
                            bool error = _checkNPIResponseForError(ms);
                            if (error && numberOfRetreis < 5)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }
               else if (error && numberOfRetreis == 5)
           {
throw new WebFaultException<NMSExceptionDetail>(new NMSExceptionDetail() { ErrorCode = ExceptionErrorCode.GeneralError, Description = "HIPPA Service is down." }, HttpStatusCode.InternalServerError);
           }

                           responseMemStream.Seek(0, SeekOrigin.Begin);
                            resp.Close();
                XmlSerializer ser = new XmlSerializer(typeof(NPIList));
          var npiResponse = (NPIList)ser.Deserialize(responseMemStream);

                            if (npiResponse != null)
                                return npiResponse.NPI;
                        }
                        break;
                    }
                    return npiRecords;
                }
                catch (Exception ex)
                {
                    throw _convertToWebFaultException(ex);
                }
            }
        }

I have to write unit test case.

Please let me know how can I mock the response and validate with results.

I have tried with the below testcase but not able to proceed/how to mock the response for 3rd party service.

[Theory, AutoSvcDomainData]
public void GetData_Returns_Collection(string npiCode, string  entityType, string name, string address1, string address2, string state, string city, string zip,string firstName,int pageNo,int pageSize, NPIRecord[] npiRecords, NPIDataService sut)
        {
            var fixture = new Fixture();
            fixture.Register<string>(() => "1");
            var entityCode = fixture.Create<string>();

           var results = sut.GetData(npiCode, entityCode, name, firstName, address1, address2, state, city, zip, pageNo, pageSize);
            Assert.Equal(results, npiRecords);
        }
stuartd
  • 70,509
  • 14
  • 132
  • 163
AMDI
  • 895
  • 2
  • 17
  • 40
  • 1
    Since there's a hard-coded call to `WebRequest.Create` in that method, you can't mock it. – Mark Seemann Mar 11 '16 at 12:50
  • Please guide me if its possible to write Unit test cases in this scenario. – AMDI Mar 11 '16 at 12:54
  • 1
    You'll need to invert the dependency in order to enable testing. See e.g. [my book](http://amzn.to/12p90MG) for detailed guidance about dependency injection. – Mark Seemann Mar 11 '16 at 13:17
  • Thanks @MarkSeemann, I don't have much time,if possible can you let me know which chapter will give me better idea to implement. – AMDI Mar 11 '16 at 13:43

0 Answers0