How to unit test a method with HttpWebRequest/Response dependencies - unit-testing

Been trying to unit test this method but can't figure out how to do it.
public bool ValidateCaptcha(string captchaResponse, string captchaChallenge,
string hostip)
{
var strPrivateKey = _secConfiguration.CaptchaPrivateKey;
var strParameters = "verify?privatekey=" + strPrivateKey +
"&remoteip=" + hostip +
"&challenge=" + captchaChallenge+
"&response=" + captchaResponse;
var url = CaptchaUrl + strParameters;
var request = CreateHttpWebRequest(url);
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
request.ContentType = "text/html";
request.ContentLength = 0;
var response = GetHttpWebResponse(request);
var writer = response.GetResponseStream();
var reader = new StreamReader(writer);
var responseFromServer = reader.ReadToEnd();
var serverResponse = responseFromServer.Split('\n');
return serverResponse[0] == "true";
}
private HttpWebResponse GetHttpWebResponse(HttpWebRequest request)
{
return (HttpWebResponse) request.GetResponse();
}
private HttpWebRequest CreateHttpWebRequest(string url)
{
return (HttpWebRequest) WebRequest.Create(url);
}
I had planned to moq the dependencies and have a couple of wrap classes
public class WrapHttpWebRequest : IHttpWebRequest
{
private readonly HttpWebRequest _request;
public WrapHttpWebRequest(HttpWebRequest request)
{
_request = request;
}
public string Method
{
get { return _request.Method; }
set { _request.Method = value; }
}
public IHttpWebResponse GetResponse()
{
return new WrapHttpWebResponse((HttpWebResponse)_request.GetResponse());
}
}
and
public class WrapHttpWebResponse : IHttpWebResponse
{
private WebResponse _response;
public WrapHttpWebResponse(HttpWebResponse response)
{
_response = response;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_response != null)
{
((IDisposable)_response).Dispose();
_response = null;
}
}
}
public Stream GetResponseStream()
{
return _response.GetResponseStream();
}
}
But can't find a way to inject them. Any ideas how can I do this? Thanks.

You could create testable version of your class under test.
Make the method virtual and override it in the testable version.
protected virtual HttpWebRequest CreateHttpWebRequest(string url)
{
return (HttpWebRequest)WebRequest.Create(url);
}
public class TesableClassUnderTest : ClassUnderTest
{
public HttpWebRequest HttpWebRequestFake { get; set; }
protected override HttpWebRequest CreateHttpWebRequest(string url)
{
if (HttpWebRequestFake != null)
return HttpWebRequestFake;
return base.CreateHttpWebRequest(url);
}
}
Then in test set the fake object to your own value:
[TestMethod]
public void test()
{
TesableClassUnderTest cut = new TesableClassUnderTest();
cut.HttpWebRequestFake = CreateFakeHttpWebRequest();
cut.ValidateCaptcha(...)
Assert...
}

Related

consuming asmx webservice in xamarin forms

I am working on a login page in Xamarin forms and I need to consume an asmx webservice in order to connect to the sql server. I used this example: https://github.com/fabiosilvalima/FSL.ConsummingAsmxServicesInXamarinForms, and tried to apply the same steps for my app. but I got an error.
here's my code:
ILogin.cs:
namespace App33.Models
{
public interface ILogin
{
string Error { get; set; }
bool ValidUser { get; set; }
}
}
ILoginSoapService.cs
public interface ILoginSoapService
{
Task<List<ILogin>> Login(string namee, string passs);
}
in App.xaml.cs
private static ILoginSoapService _loginSoapService;
public static ILoginSoapService LoginSoapService
{
get
{
if (_loginSoapService == null)
{
_loginSoapService = DependencyService.Get<ILoginSoapService>();
}
return _loginSoapService;
}
Main.xaml.cs
public MainPage()
{
InitializeComponent();
}
async void OnButtonClicked(object sender, EventArgs e)
{
var entr_usrname = this.FindByName<Entry>("username");
string usrname = entr_usrname.Text;
var entr_pass = this.FindByName<Entry>("Password");
string pass = entr_pass.Text;
var state = await App.LoginSoapService.Login(usrname,pass);
if (state[0].ValidUser == true)
{
await DisplayAlert("Alert", "You have been alerted", "OK");
}
}
this is for the portable app. my webservice is added to the web reference as LoginWs. it has the following codes:
Result.cs:
public class Result
{
public string Error { get; set; }
public bool ValidUser { get; set; }
}
WebService1.asmx.cs:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Result Login(string userName, string userPass)
{
SqlConnection conn=new SqlConnection (new DBConnection().ConnectionString);
Result result = new Result();
try
{
SqlCommand cmd = new SqlCommand("SELECT userName, password FROM users where CONVERT(VARCHAR, username)=#username and CONVERT(VARCHAR, password)=#password");
cmd.Parameters.AddWithValue("username", userName);
cmd.Parameters.AddWithValue("password", userPass);
cmd.Connection = conn;
if (conn.State==System.Data.ConnectionState.Closed)
{
conn.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
result.ValidUser = true;
return result;
}
else
{
result.ValidUser = false;
}
}
catch(Exception ex)
{
result.Error = ex.ToString();
}
finally
{
conn.Close();
}
return result;
}
}
}
now in App.Android:
Result.cs
namespace App33.Droid.LoginWs
{
public partial class Result : ILogin
{
}
}
LoginSoapService.cs
[assembly: Dependency(typeof(App33.Droid.LoginSoapService))]
namespace App33.Droid
{
public sealed class LoginSoapService :ILoginSoapService
{
LoginWs.WebService1 service;
public LoginSoapService()
{
service = new LoginWs.WebService1()
{
// Url = "http://codefinal.com/FSL.ConsummingAsmxServicesInXamarinForms/Customers.asmx" //remote server
Url = "http://192.168.0.106/site2/WebService1.asmx" //localserver - mobile does not understand "localhost", just that ip address
};
}
public async Task<List<ILogin>> Login( string namee,string pass)
{
return await Task.Run(() =>
{
var result = service.Login(namee,pass);
return new List<ILogin>(result);
});
}
}
}
the error i'm getting is in this line:return new List(result);. it says: Error CS1503 Argument 1: cannot convert from 'App33.Droid.LoginWs.Result' to 'int'. I can't figure out what the peoblem is. sorry for the long question. any help is appreciated.

WebTestClient does not post object

I am trying to perform simple test of reading method. I am trying to work with reactive approach so to test whole context I am using WebTestClient. Although post method seems to work correctly reading operation is not working. But why? Isn't it should be saved to embedded mongo database?
Do I need to wait for it somehow if this is reactive?
Exception is thrown definitely in service because I am seeing
com.geborskimateusz.util.exceptions.NotFoundException: No product found for productId: 1
This is how test looks like:
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = RANDOM_PORT, properties = {"spring.data.mongodb.port: 0"})
public class MovieServiceApplicationTests {
#Autowired
WebTestClient webTestClient;
#Autowired
MovieService movieService;
#Test
public void getMovie() {
Integer given = 1;
postAndVerify(given, HttpStatus.OK);
Movie movie = movieService.getMovie(given); **fails here**
assertNotNull(movie);
getAndVerify(given, HttpStatus.OK);
}
private WebTestClient.BodyContentSpec postAndVerify(Integer id, HttpStatus httpStatus) {
Movie movie = Movie.builder()
.movieId(id)
.title("Title for movie " + id)
.genre("Genre for movie " + id)
.address("Address for movie " + id)
.build();
return webTestClient.post()
.uri("/movie")
.body(Mono.just(movie), Movie.class)
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.expectStatus().isEqualTo(httpStatus)
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.expectBody();
}
private WebTestClient.BodyContentSpec getAndVerify(Integer id, HttpStatus httpStatus) {
return webTestClient.get()
.uri("/movie/" + id)
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.expectStatus().isEqualTo(httpStatus)
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.expectBody()
.jsonPath("$.movieId").isEqualTo(id)
.jsonPath("$.genre").isNotEmpty()
.jsonPath("$.title").isNotEmpty()
.jsonPath("$.address").isNotEmpty();
}
}
Service and repository are very simple implementations:
Service:
#Slf4j
#RestController
public class BaseMovieService implements MovieService {
private final ServiceUtil serviceUtil;
private final MovieRepository movieRepository;
private final MovieMapper movieMapper = MovieMapper.INSTANCE;
#Autowired
public BaseMovieService(ServiceUtil serviceUtil, MovieRepository movieRepository) {
this.serviceUtil = serviceUtil;
this.movieRepository = movieRepository;
}
#Override
public Movie getMovie(Integer movieId) {
if (movieId < 1) throw new InvalidInputException("Invalid productId: " + movieId);
MovieEntity movieEntity = movieRepository.findMovieById(movieId)
.orElseThrow(() -> new NotFoundException("No product found for productId: " + movieId));
Movie movie = movieMapper.entityToApi(movieEntity);
movie.setAddress(serviceUtil.getServiceAddress());
log.debug("/movie return the found movie for movieId={}", movieId);
return movie;
}
#Override
public Movie createMovie(Movie movie) {
try {
MovieEntity movieEntity = movieMapper.apiToEntity(movie);
MovieEntity saved = movieRepository.save(movieEntity);
log.debug("createMovie: entity created for movieId: {}", movie.getMovieId());
return movieMapper.entityToApi(saved);
}catch (DuplicateKeyException e) {
throw new InvalidInputException("Duplicate key for movieId: " +movie.getMovieId());
}
}
#Override
public void deleteMovie(Integer movieId) {
}
}
And repo:
public interface MovieRepository extends PagingAndSortingRepository<MovieEntity, String> {
Optional<MovieEntity> findMovieById(Integer movieId);
}
This is however strange because I am sure that repo work fine, all tests below are passing:
#ExtendWith(SpringExtension.class)
#DataMongoTest
public class MovieRepositoryTest {
public static final int BASE_MOVIE_ID = 1;
#Autowired
MovieRepository movieRepository;
MovieEntity savedMovieEntity;
#BeforeEach
void setUp() {
movieRepository.deleteAll();
MovieEntity movieEntity = MovieEntity
.builder()
.movieId(BASE_MOVIE_ID)
.title("Raise of Jedi")
.address("123.321.54x24")
.genre("Sci-Fi")
.build();
savedMovieEntity = movieRepository.save(movieEntity);
assertEqualsMovie(movieEntity, savedMovieEntity);
}
#Test
void create() {
MovieEntity movieEntity = MovieEntity
.builder()
.movieId(2)
.title("Fall of Jedi")
.address("125.721.54x24")
.genre("Sci-Fi")
.build();
MovieEntity saved = movieRepository.save(movieEntity);
assertEqualsMovie(movieEntity, saved);
assertEquals(2, movieRepository.count());
}
#Test
void update() {
String givenTitle = "Updated Title";
savedMovieEntity.setTitle(givenTitle);
MovieEntity updated = movieRepository.save(savedMovieEntity);
assertEquals(givenTitle, updated.getTitle());
}
#Test
void findById() {
Optional<MovieEntity> optionalMovieEntity = movieRepository.findById(savedMovieEntity.getId());
assertTrue(optionalMovieEntity.isPresent());
MovieEntity movieEntity = optionalMovieEntity.get();
assertEqualsMovie(savedMovieEntity, movieEntity);
}
#Test
void shouldPerformOptimisticLocking() {
String concurrentM1actionData = "Concurrent action data performed on M1";
String concurrentM2actionData = "Concurrent action data performed on M2";
MovieEntity m1 = movieRepository.findById(savedMovieEntity.getId()).get();
MovieEntity m2 = movieRepository.findById(savedMovieEntity.getId()).get();
m1.setTitle(concurrentM1actionData);
// by updating Entity its version should be updated
movieRepository.save(m1);
// should fail because of version mismatch
try {
m2.setTitle(concurrentM2actionData);
movieRepository.save(m2);
fail("Expected an OptimisticLockingFailureException");
} catch (OptimisticLockingFailureException e) {
System.out.println("shouldPerformOptimisticLocking() -> catch OptimisticLockingFailureException");
}
//check current version and state
MovieEntity updatedMovieEntity = movieRepository.findById(savedMovieEntity.getId()).get();
assertEquals(1, (int) updatedMovieEntity.getVersion());
assertEquals(concurrentM1actionData, updatedMovieEntity.getTitle());
}
#Test
void delete() {
movieRepository.delete(savedMovieEntity);
assertEquals(0, movieRepository.count());
}
#Test
void duplicateMovieError() {
MovieEntity duplicate = MovieEntity.builder().build();
duplicate.setId(savedMovieEntity.getId());
assertThrows(DuplicateKeyException.class, () -> movieRepository.save(duplicate));
}
#Test
void paging() {
bulkSaveMovie();
Pageable nextPage = PageRequest.of(0, 4, Sort.Direction.ASC, "movieId");
nextPage = verifyPages(nextPage, "[1, 2, 3, 4]", true);
nextPage = verifyPages(nextPage, "[5, 6, 7, 8]", true);
verifyPages(nextPage, "[9, 10]", false);
}
private Pageable verifyPages(Pageable nextPage, String idsAsString, boolean hasNext) {
Page<MovieEntity> moviePage = movieRepository.findAll(nextPage);
assertEquals(hasNext, moviePage.hasNext());
String ids = moviePage.get().map(MovieEntity::getMovieId).collect(Collectors.toList()).toString();
assertEquals(idsAsString, ids);
return nextPage.next();
}
private void bulkSaveMovie() {
movieRepository.deleteAll();
List<MovieEntity> movies = IntStream.rangeClosed(1, 10)
.mapToObj(i -> MovieEntity.builder()
.movieId(i)
.title("Movie nr: " + i)
.build())
.collect(Collectors.toList());
movieRepository.saveAll(movies);
}
private void assertEqualsMovie(MovieEntity expected, MovieEntity actual) {
assertAll("Executing assertEqualsMovie(..)", () -> {
assertEquals(expected.getId(), actual.getId());
assertEquals(expected.getVersion(), actual.getVersion());
assertEquals(expected.getMovieId(), actual.getMovieId());
assertEquals(expected.getTitle(), actual.getTitle());
assertEquals(expected.getAddress(), actual.getAddress());
assertEquals(expected.getGenre(), actual.getGenre());
});
}
}

On using swipe refresh in recyclerview my adapter is not getting data when it is refreshing

My Latest fragment
public class Latest extends Fragment {
private RecyclerView recyclerLatest;
private SwipeRefreshLayout swipeRecycler;
private RecyclerView.LayoutManager mLayoutManager;
private List<LatestAdDetails> latestAdDetailsList = new ArrayList<>();
private LatestAdapter latestAdapter;
private LatestAdDetails latestAdDetails,latestAdDetails1;
private JSONObject jsonobject;
private Context context;
private String x;
public Latest() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView=inflater.inflate(R.layout.latest_fragment,container,false);
recyclerLatest = (RecyclerView) mainView.findViewById(R.id.recycler_latest);
swipeRecycler= (SwipeRefreshLayout)mainView.findViewById(R.id.swipe_recycler_latest);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerLatest.setLayoutManager(mLayoutManager);
recyclerLatest.setHasFixedSize(true);
context = getContext();
// url for latest add obtaining
UrlConstants.latest_ad_obtained= UrlConstants.latest_ad+ AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+AppController.getString(getActivity().getApplicationContext(),"city_id");
latestAdapter = new LatestAdapter(latestAdDetailsList);
recyclerLatest.setAdapter(latestAdapter);
latestAdd();
swipeRecycler.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(){refreshLatestAd();
}
});
return mainView;
}
private void refreshLatestAd() {
UrlConstants.latset_ad_refresh_obtained=UrlConstants.latest_ad_refresh+
AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"city_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"refresh_ad")+"/"+0;
LatestRefreshHandler latestRefreshHandler = new LatestRefreshHandler("latestRefreshADD");
latestRefreshHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
latestAdapter.clear();
int Ad_id_refresh = jsonarray.getJSONObject(jsonarray.length()).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.addAll(latestAdDetailsList);
latestAdapter.notifyDataSetChanged();
recyclerLatest.setAdapter(latestAdapter);
swipeRecycler.setRefreshing(false);
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}
private void latestAdd() {
LatestRequestHandler latestHandler = new LatestRequestHandler("latestADD");
latestHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
int Ad_id_refresh = jsonarray.getJSONObject(1).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.notifyDataSetChanged();
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}}
my Adapter class
public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.MyViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String text;
private List<LatestAdDetails> latestAddDetailsList;
public LatestAdapter(List<LatestAdDetails> latestAddDetailsList) {
this.latestAddDetailsList = latestAddDetailsList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle, txtDescription, txtCityName, txtPrice, txtCategory, txtHour, txtPhotoNo;
private NetworkImageView imgPhoto;
public MyViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_fad);
txtDescription = (TextView) itemView.findViewById(R.id.description_fad);
txtCityName = (TextView) itemView.findViewById(R.id.city_name_fad);
txtPrice = (TextView) itemView.findViewById(R.id.price_fad);
txtCategory = (TextView) itemView.findViewById(R.id.category_fad);
txtHour = (TextView) itemView.findViewById(R.id.hours_fad);
txtPhotoNo = (TextView) itemView.findViewById(R.id.txt_photo_no_fad);
imgPhoto = (NetworkImageView) itemView.findViewById(R.id.img_photo_lod_fad);
}
}
public void clear() {
latestAddDetailsList.clear();
notifyDataSetChanged();
}// Add a list of items
public void addAll(List<LatestAdDetails> list) {
latestAddDetailsList.addAll(list);
notifyDataSetChanged();
}
#Override
public LatestAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.featured_ad_adapter_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(LatestAdapter.MyViewHolder holder, int position) {
LatestAdDetails latestAddDetails = latestAddDetailsList.get(position);
holder.txtTitle.setText(translate(latestAddDetails.getTitle()));
holder.txtDescription.setText(translate(latestAddDetails.getDescription()));
holder.txtCityName.setText(translate(latestAddDetails.getCityName()));
holder.txtPrice.setText(Integer.toString(latestAddDetails.getPrice()));
holder.txtCategory.setText(translate(latestAddDetails.getCategoryName()));
holder.txtHour.setText(Integer.toString(latestAddDetails.getCreated()));
holder.txtPhotoNo.setText(Integer.toString(0) + " photos ");
try {
imageLoader = VolleyHandler.getImageLoader();
} catch (Exception e) {
e.printStackTrace();
}
holder.imgPhoto.setImageUrl(latestAddDetails.getDefault_photo(), imageLoader);
}
#Override
public int getItemCount() {
Log.e("size", String.valueOf(latestAddDetailsList.size()));
return latestAddDetailsList.size();
}
private String translate(String myString) {
try {
myString = myString.replace("\n", "").replace("\r", "");
byte[] utf8Bytes = myString.getBytes("UTF8");
text = new String(utf8Bytes, "UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return text;
}}
on refreshing adapter size is zero,but getting json correctly,but not adding to adapter,and the recycler view is not showing new data,please help me ,the json is giving 10 datas on every swipe but it is not getting added to recyclerview
It seems like a logical bug :
In method : refreshLatestAd(), Remove these line :
latestAdapter.clear();
latestAdapter.addAll(latestAdDetailsList);
and
recyclerLatest.setAdapter(latestAdapter); // It need not be set again.
Let me know if it helps.
latestAdapter.notifyDataSetChanged() is sufficient to notify the
adapter that the data is changed. Always modify the list
[latestAdDetailsList] which is being set to adapter, this is the sure
shot way to make the changes reflect when you call notifyDataSetChanged.

Xamarin Async and Await: UI thread is getting blocked

I have this architecture in my project and sometimes UI thread is getting blocked, can someone please explain what is happening with the below code. Thanks
I am making a service call asyncronously from xamarin.forms viewmodel
Following is the flow
View--->ViewModel---ClassA--->ClassB--Make a service call from here
Code
Scenario 1
public partial class HomePage : ContentPage
{
private HomeVM model;
public HomePage()
{
InitializeComponent();
model = new HomeVM();
model.MainText = ReturnBool().Result;
this.BindingContext = model;
}
public async Task<string> ReturnBool()
{
IsBusy = true;
var r = await new WS().ReturnBool();
IsBusy = false;---------------------------------------Not hitting the breakpoint here
return r;
}
}
public interface IWS
{
Task<string> ReturnBool();
}
public class WS : IWS
{
public Task<string> ReturnBool()
{
return ServiceOperations.ReturnBool();
}
}
internal class ServiceOperations
{
public async static Task<string> ReturnBool()
{
var uri = new Uri(string.Format("http://testmyapi.azurewebsites.net/", string.Empty));
try
{
HttpClient client = new HttpClient();
client.BaseAddress = uri;
HttpResponseMessage response = null;
response = await client.GetAsync("/api/Values/Get");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
string str = JsonConvert.DeserializeObject<string>(content);
return str;
}
else {
return null;
}
}
catch (Exception)
{
return null;
}
}
}
Scenario 2
public partial class HomePage : ContentPage
{
private HomeVM model;
public HomePage()
{
InitializeComponent();
model = new HomeVM();
this.BindingContext = model;
}
}
public class HomeVM : BaseVM
{
private string mainText;
public string MainText
{
get { return mainText; }
set
{
mainText = value;
RaisePropertyChanged("MainText");
}
}
public HomeVM()
{
MainText = ReturnBool().Result;
}
public async Task<string> ReturnBool()
{
IsBusy = true;
var r = await new WS().ReturnBool();
IsBusy = false;---------------------------------------Not hitting the breakpoint here
return r;
}
}
public interface IWS
{
Task<string> ReturnBool();
}
public class WS : IWS
{
public Task<string> ReturnBool()
{
return ServiceOperations.ReturnBool();
}
}
internal class ServiceOperations
{
public async static Task<string> ReturnBool()
{
var uri = new Uri(string.Format("http://testmyapi.azurewebsites.net/", string.Empty));
try
{
HttpClient client = new HttpClient();
client.BaseAddress = uri;
HttpResponseMessage response = null;
response = await client.GetAsync("/api/Values/Get");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
string str = JsonConvert.DeserializeObject<string>(content);
return str;
}
else {
return null;
}
}
catch (Exception)
{
return null;
}
}
}
You are using ReturnBool().Result in the constructor. The return call will block your UI thread. Move that code to the controller action methods without using ".Result" part. Ensure that the methods are async and always return a Task.

Mocking, Unit Testing (NUnit) setup problem with HttpHandler

This post relates to two other posts, here and here.
I'm new to Unit Testing & Mocking. I have a test fixture that is trying to mock a HttpContext object including the response and request. I think the test code is not setup properly, as after calling the handler I get an error immediately. There error I am getting is:
UnitTests.UADHandlerFixture.Request_Is_Object:
System.NullReferenceException : Object reference not set to an instance of an object.
at Abstract.BaseHttpHandler.get_Request() in BaseHttpHandler.cs:line 21
at Abstract.BaseHttpHandler.get_IsRequestFromUAD() in BaseHttpHandler.cs:line 23
at Handlers.UADTimeHttpHandler.ProcessRequest(HttpContextBase context) in UADTimeHttpHandler.cs:line 19
at UnitTests.UADHandlerFixture.Request_Is_Object() in UADHttpHanderTests.cs:line 47
The test code is this:
[TestFixture]
public class UADHandlerFixture
{
private Mock<HttpContextBase> _mockHttpContext;
private Mock<HttpRequestBase> _mockHttpRequest;
private Mock<HttpResponseBase> _mockHttpResponse;
private UADTimeHttpHandler _handler;
private WindsorContainer _container;
[SetUp]
public void Init()
{
_mockHttpRequest = new Mock<HttpRequestBase>();
_mockHttpResponse = new Mock<HttpResponseBase>();
_mockHttpContext = new Mock<HttpContextBase>();
_container = new WindsorContainer();
_container.AddComponent<ILogger, FakeLogger>();
_container.AddComponent<IDataRepository, FakeDataRepository>();
_mockHttpContext.SetupGet(x => x.Application[0]).Returns(_container);
_mockHttpContext.SetupGet(x => x.Request).Returns(_mockHttpRequest.Object);
_mockHttpContext.SetupGet(x => x.Response).Returns(_mockHttpResponse.Object);
_handler = new UADTimeHttpHandler();
}
[Test]
public void Request_Is_Object()
{
_handler.ProcessRequest(_mockHttpContext.Object);
}
}
Handler:
public class UADTimeHttpHandler : BaseHttpHandler
{
public override void ProcessRequest(HttpContextBase context)
{
if (IsRequestFromUAD)
{
Logger.Log("Log stuff");
DataRepository.Write("DB stuff");
ReturnResponse(HttpStatusCode.OK, DateTime.Now.ToString());
}
else
ReturnResponse(HttpStatusCode.BadRequest);
}
}
BaseHandler:
public abstract class BaseHttpHandler : IHttpHandler
{
private HttpContext _httpContext;
private ILogger _logger;
private IDataRepository _dataRepository;
protected ILogger Logger { get { return _logger; } }
protected IDataRepository DataRepository { get { return _dataRepository; } }
protected HttpContext Context { get { return _httpContext; } }
protected HttpRequest Request { get { return _httpContext.Request; } }
protected HttpResponse Response { get { return _httpContext.Response; } }
protected bool IsRequestFromUAD { get { return Request.UserAgent == null ? false : Request.UserAgent.Equals("UAD"); } }
public virtual bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
WindsorContainer container = (WindsorContainer)context.Application[0];
_logger = container.Resolve<ILogger>();
_dataRepository = container.Resolve<IDataRepository>();
_httpContext = context;
ProcessRequest(new HttpContextWrapper(context));
}
protected virtual void ReturnResponse(HttpStatusCode httpStatus)
{
Response.StatusCode = (int)httpStatus;
}
protected virtual void ReturnResponse(HttpStatusCode httpStatus, string response)
{
Response.StatusCode = (int)httpStatus;
Response.Write(response);
}
protected virtual string GetInputStream()
{
using (var reader = new StreamReader(Request.InputStream))
{
return reader.ReadToEnd();
}
}
public abstract void ProcessRequest(HttpContextBase context);
}