Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written a unit test for a method so every thing is working properly but there is only one issue with one mock object ,that object is always returning null value

Mocking of Get Token Method always returning null

What I have tried:

this is the unit test which I have written in this everything is working properly except GetToken method after mocking this method always returning null value

public void UserRegistrationUnitTest()
      {
          RegistrationDTO inputParameters = new RegistrationDTO()
          {
              CountryCode="IN",
              Email="abc.abc@abc.com",
              FirstName="Abc",
              LastName="Abc",
              IsChild=0,
              Password="abc@12345",
              ReuseEmailAddress=0,
              TermsofUseAgreed=Confirm.Yes,
              UserName="abc123"
          };



          CountryList expectedOutputCountryData = new CountryList()
          {
             en=new List<En>()
             {
                 new En { name="AF",value="Afghanistan"},
                 new En { name="AX",value="Åland Islands"},
                 new En { name="AL",value="Albania"},
                 new En { name="DZ",value="Algeria"},
                 new En { name="IN",value="India"}
             }
          };
          RegistrationSuccessDTO DTOOutput = new RegistrationSuccessDTO() { ApprovalNeeded =false, Communication = "" };
          HttpResponseMessage expectedOutputUserReg = new HttpResponseMessage()
          {
              StatusCode = HttpStatusCode.OK,
              Content = new StringContent(JsonConvert.SerializeObject(DTOOutput))
          };

          LoginAuthDTO objInput = new LoginAuthDTO() { Username = inputParameters.UserName, Password = inputParameters.Password };
          TokenDTO objOuptput = new TokenDTO()
          {
              AccessToken = CommonUtility.AccessToken
          };
          HttpResponseMessage fout = new HttpResponseMessage()
          {
              StatusCode = HttpStatusCode.OK,
              Content =new StringContent(JsonConvert.SerializeObject(objOuptput))
          };
          //setting the mock for countrylist
          string serilizeCountrylst = JsonConvert.SerializeObject(expectedOutputCountryData);
          objMockIJsonReadDeserializeUtility.Setup(x => x.ReadJsonandDeserialize<CountryList>("Data/Countries.json")).Returns(expectedOutputCountryData);

          //setting the mock for UserRegistration
          objMockIRegistrationMEEService.Setup(x => x.UserRegistration(inputParameters)).Returns(Task.FromResult(expectedOutputUserReg));

          //setting the mock for GetTokenMethod
          objMockITokenApplicationService.Setup(x => x.GetToken(objInput)).Returns(Task.FromResult(fout));
          //call the actual method
          HttpResponseMessage finalOutput=objRegistrationService.UserRegistration(inputParameters).Result;

          string finalcontent = finalOutput.Content.ReadAsStringAsync().Result;

          CountryList contriesOutPut = objMockIJsonReadDeserializeUtility.Object.ReadJsonandDeserialize<CountryList>("Data/Countries.json");
          RegistrationSuccessDTO registrationOutput = JsonConvert.DeserializeObject<RegistrationSuccessDTO>(((StringContent)objMockIRegistrationMEEService.Object.UserRegistration(inputParameters).Result.Content).ReadAsStringAsync().Result);
          Assert.NotNull(registrationOutput);
          Assert.NotNull(contriesOutPut);
          Assert.NotNull(finalcontent);
      }



Actulal Method

public async Task<HttpResponseMessage> UserRegistration(RegistrationDTO registrationDTO)
       {
           CountryList lstCountryList = _ijsonReadDeserializeUtility.ReadJsonandDeserialize<CountryList>("Data/Countries.json");

           var checkcountry = lstCountryList.en.Any(x=>x.name == registrationDTO.CountryCode);

           if (checkcountry)
           {
               if (Regex.IsMatch(registrationDTO.Email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase))
               {
                   if (registrationDTO.TermsofUseAgreed == Confirm.Yes)
                   {
                       var response = await _registrationMEEService.UserRegistration(registrationDTO);
                       string strContentString = await response.Content.ReadAsStringAsync();

                       if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                       {
                           return response;
                       }
                       else if (response.StatusCode == System.Net.HttpStatusCode.OK)
                       {
                           RegistrationSuccessDTO responseobject = JsonConvert.DeserializeObject<RegistrationSuccessDTO>(strContentString);

                           if (!responseobject.ApprovalNeeded)
                           {
                               LoginAuthDTO authParams = new LoginAuthDTO() { Username = registrationDTO.UserName, Password = registrationDTO.Password };

                               var tokenResponse = await _tokenApplicationService.GetToken(authParams);

                               if (tokenResponse != null && tokenResponse.IsSuccessStatusCode)
                               {
                                   string contentString = await tokenResponse.Content.ReadAsStringAsync();

                                   TokenDTO tokenDTO = JsonConvert.DeserializeObject<TokenDTO>(contentString);

                                   List<object> lstTokenRegistration = new List<object>();
                                   lstTokenRegistration.Add(tokenDTO);
                                   lstTokenRegistration.Add(responseobject);

                                   return new HttpResponseMessage()
                                   {
                                       StatusCode = HttpStatusCode.OK,
                                       Content = new StringContent(JsonConvert.SerializeObject(lstTokenRegistration),
                                                      Encoding.UTF8, "application/json")
                                   };
                               }
                               else
                               {
                                   return new HttpResponseMessage()
                                   {
                                       StatusCode = HttpStatusCode.Unauthorized,
                                       Content = new StringContent(JsonConvert.SerializeObject(new MEEError() { Error = "UnAuthorised User", ErrorDescription = "User UnAuthorised" }),
                                              Encoding.UTF8, "application/json")
                                   };
                               }

                           }
                           else
                           {
                               return new HttpResponseMessage()
                               {
                                   StatusCode = HttpStatusCode.OK,
                                   Content = new StringContent(JsonConvert.SerializeObject(responseobject),
                                                  Encoding.UTF8, "application/json")
                               };
                           }

                       }
                       else
                       {
                           return response;
                       }
                   }
                   else
                   {
                       return new HttpResponseMessage()
                       {
                           StatusCode = HttpStatusCode.BadRequest,
                           Content = new StringContent(JsonConvert.SerializeObject(new MEEError() { Error = "AgreedTerms&ConditionError", ErrorDescription = "Please check Terms and Condition" }),
                                          Encoding.UTF8, "application/json")
                       };
                   }
               }
               else
               {
                   return new HttpResponseMessage()
                   {
                       StatusCode = HttpStatusCode.BadRequest,
                       Content = new StringContent(JsonConvert.SerializeObject(new MEEError() { Error = "InValidMailFormat", ErrorDescription = "Enter Valid Email" }),
                                          Encoding.UTF8, "application/json")
                   };
               }
           }
           else
           {
               return new HttpResponseMessage()
               {
                   StatusCode =HttpStatusCode.BadRequest,
                   Content = new StringContent(JsonConvert.SerializeObject(new MEEError() { Error = "InvalidCountryCode", ErrorDescription ="Enter Valid Country Code"  }),
                                          Encoding.UTF8, "application/json")
               };
           }

       }
Posted
Updated 30-Oct-19 23:33pm
v2
Comments
Richard MacCutchan 31-Oct-19 5:24am    
Please do not just dump a load of unformatted code here and expect someone (who has never seen it before) to analyse, and debug, it for you. Just show the extract of the code where the error occurs, and explain exactly where and what error it is. And put the code between <pre> tags so it is properly readable.
F-ES Sitecore 31-Oct-19 5:37am    
Use the debugger to step through the code and work out why it is returning null. That code is too complex and involving external info like classes and text files for anyone to easily test it.
Member 12749751 31-Oct-19 5:41am    
But debugger is not stepping into the method Gettoken() to check further
Afzaal Ahmad Zeeshan 31-Oct-19 5:44am    
Then try to debug a wrapping function that further calls this method.
Afzaal Ahmad Zeeshan 31-Oct-19 5:43am    
Would be great to debug the code and see what causes it to return null.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900