Tuesday, June 21, 2022

Android Test Automation with Espresso


What is Espresso?

  • It automatically synchronises your test actions with user interface of your application.
  • Framework also, ensure that your activity is started before the test runs. It also, lets the test wait until all observed background activities have finished 
  • The framework prevents direct access to activities and views of the application because holding on to these objects and operating on them off the UI thread is a major source of test flakiness. Thus, you will not see methods like getView() and getCurrentActivity() in the Espresso API. 
  • You can still safely operate on views by implementing your own subclasses of ViewAction and ViewAssertion.



UI test for single apps: 
  • verify that target app behaves as expected when user performs a specific action or enters specific input in activities 
  • it allows you to check that target app returns the correct UI output in response to user interactions in the app activities
  • Espresso allows you to simulate user actions and test complex app user interactions 

UI test for multiple apps:
  • this type of test provide the correct behaviour of interaction b/w different user apps or between user apps and system apps.
  • eg. you want to test that your camera app share images correctly with 3rd party social media application or with default android photo application 
  • UI Automator allows you to create such scenarios

API components

To Automate, we need 3 basic things i.e. find something, do something and check something

The main components of Espresso include the following:

  • Espresso – Entry point to interactions with views (via onView() and onData()). Also exposes APIs that are not necessarily tied to any view, such as pressBack().
  • ViewMatchers – 
    • Allows to find view in current view hierarchy (Find Something).
    • A collection of objects that implement the Matcher<? super View> interface. You can pass one or more of these to the onView() method to locate a view within the current view hierarchy.
  • ViewActions – 
    • allows to perform actions on the views (Do Something).
    • A collection of ViewAction objects that can be passed to the ViewInteraction.perform()method, such as click().
  • ViewAssertions – 
    • allows to alert state of a view (Check Something)
    • A collection of ViewAssertion objects that can be passed theViewInteraction.check()method. Most of the time, you will use the matches assertion, which uses a View matcher to assert the state of the currently selected view.


Espresso Test Recorder

Pros of Espresso Test Recorder
  • Allows to create effective UI based test cases with user interactions
  • we can capture assertions and interactions without accessing app's structure directly which increases execution speed and optimises test cases.
  • It saves lot of time to search for locators and then writing test cases.
  • It supports multiple assertions making more reliable test cases.
Cons of Espresso Test Recorder
  • Currently does not Support Recording of Web Views interactions
  • Once we complete Recording once for next time Recording it launches the app there is no API to control such behaviour.
  • Cann't record Assertions for Toast Messages.


Pros

  • Supported for all android versions
  • simpler and quicker to setup
  • supports Jacoco to measure code coverage
  • extensive testing is possible as it covers many UI actions and gestures (toast messages, camera activity, etc.)

Cons

  • The test cases are written inside android application project code and hence building project to run test case takes lot of time.




Gradle is used to give instructions for building your project based on instructions that you give in build.gradle file.




Chapter 1. Introduction to Espresso




 










What is AndroidX?



















Chapter 2. Setting up Espresso













 


Chapter 3. Writing the First Test




https://developer.android.com/training/testing/espresso/cheat-sheet





Friday, June 3, 2022

RESTful Web Service with SpringBoot



Spring Data JPA: to connect our REST API to a database. hence we can use Hibernate/JPA for this.


REST is a style of software architecture for distributed hypermedia systems

=========================================================================

# RESTful Web Services

Social media Application

User make many posts. hence, the relationship b/w user and posts is one to many.
  • Retrieve all Users -      GET /users
  • Create a User -             POST /users
  • Retrieve one User -      GET /users/{id}
  • Delete a User -             DELETE /users/{id}

  • Retrieve all posts for a User -        GET /users/{id}/posts
  • Create a posts for a User -             POST /users/{id}/posts
  • Retrieve details of a post -             GET /users/{id}/posts/{post_id}




  • We have used annotation for RestController
  • Then mapped GET request to the URI to the above method. 
  • Now, whatever my method will return, is displayed on the browser.

  • Also, we can use GetMapping, instead of RequestMapping.
========================================================================

Step 1. Enhancing the Hello World Service to return a Bean




This error means "No convertor found for return value of type".

So, If we don't create a GETTER, automatic conversion will not work.

This happened because there is not getters in HelloWorldBean class.

We have added GETTER also, to remove the above Exception.
So, variable, "message" is coming back as JSON string


=======================================================================


Now we will understand what's happening in the background?
Who is handling the request?
How HelloWorldBean content getting translated to JSON?


Step 2. RQuick Review of Spring Boot Auto Configuration and Dispatcher Servlet - What's happening in the background?

What is dispatcher servlet?
who is configuring dispatcher servlet?
What does dispatcher servlet do?
How does the HelloWorldBrean object get converted to JSON?
Who is configuring the error mapping?


============================
CONDITIONS EVALUATION REPORT
============================
This has lot of details of AutoConfiguration reports.


DispatcherServletAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet' (OnClassCondition)
      - found 'session' scope (OnWebApplicationCondition)

Above says, "DispatcherServletAutoConfiguration matched, because it found a class called DispatcherServlet "


  • We added a starter on SpringBoot Starter Web
  • SpringBoot Starter Web has dependency on spring web MVC framework
  • Hence, we got DispatcherServlet class into our classpath.
  • So, SpringBoot Autoconfiguration says, "I found DispatcherServlet on the classpath"
  • Hence, now we can configure the DispatcherServletAutoConfiguration

ErrorMvcAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet' (OnClassCondition)
      - found 'session' scope (OnWebApplicationCondition)

It says "javax.servlet.Servlet classes are found on classpath, So we would need to configure error page"

ErrorMvcAutoConfiguration#basicErrorController matched:
      - @ConditionalOnMissingBean (types: org.springframework.boot.web.servlet.error.ErrorController; SearchStrategy: current) did not find any beans (OnBeanCondition)

   ErrorMvcAutoConfiguration#errorAttributes matched:
      - @ConditionalOnMissingBean (types: org.springframework.boot.web.servlet.error.ErrorAttributes; SearchStrategy: current) did not find any beans (OnBeanCondition)

   ErrorMvcAutoConfiguration.DefaultErrorViewResolverConfiguration#conventionErrorViewResolver matched:
      - @ConditionalOnBean (types: org.springframework.web.servlet.DispatcherServlet; SearchStrategy: all) found bean 'dispatcherServlet'; @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver; SearchStrategy: all) did not find any beans (OnBeanCondition)

So, its configuring the basicErrorController, errorAttributes and conventionErrorViewResolver.

The error page that we saw earlier was White label error page. 
WhitelabelErrorViewConfiguration has generated the error page.


So, all these configurations are getting fired because of something called SpringBoot AutoConfiguration. 

SpringBoot looks at all the classes, all the jars which are available on the classpath, and based on whatever is in the classpath, it tries to auto-configure different things like DispatcherServlet.


HttpMessageConvertersAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.http.converter.HttpMessageConverter' (OnClassCondition)
      - NoneNestedConditions 0 matched 1 did not; NestedCondition on HttpMessageConvertersAutoConfiguration.NotReactiveWebApplicationCondition.ReactiveWebApplication did not find reactive web application classes (HttpMessageConvertersAutoConfiguration.NotReactiveWebApplicationCondition)

Other things that are autoconfigured are HTTP Message Converters. So, these HTTP message converters are responsible for converting to JSON.
What is happening is called Jackson to object mapper.

JacksonAutoConfiguration.Jackson2ObjectMapperBuilderCustomizerConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.http.converter.json.Jackson2ObjectMapperBuilder' (OnClassCondition)

Jackson to object mapper does the conversion from JSON to beans and beans to JSON.

Who is configuring Dispatcher Servlet?
Ans. SpringBoot AutoConfiguration

How does the HelloWorldBrean object get converted to JSON?
Ans. Because of SpringBoot AutoConfiguration as Message Converters and Jackson beans are getting initialized. 

Who is configuring the error mapping?
Ans. SpringBoot AutoConfiguration, creates a default error page for us. 


==========================================================================

Mapping servlets: dispatcherServlet urls=[/], webServlet urls=[/h2-console/*]

[/] this is the root of the web applications


Dispatcher servlet do 2 things:
  1. convert to JSON
  2. sends back the response

  • When you type the URL /hello-world-bean, the request goes to DIspatcherServlet 
    • DispatcherServlet will be the one which is handling the request first. 
    • This follows the pattern called FRONT CONTROLLER.
    • DispatcherServlet is the front controller for spring MVC Framework.
    • So request goes to DispatcherServlet
    • DispatcherServlet knows all the different mapping present in the application
    • It knows /hello-world2 and /hello-world-bean GET method is mapped to what specific method
  • Then dispatcher servlet finds the HelloWorld Controller, 
  • It calls specific method helloWorldBean(), gets the object, invokes the conversion on it,
    • So, once, DispatcherServlet gets the request, it determines that what is the right controller to execute the request, and will execute the right method of the controller
    • Once object is returned back, then dispatcherServlet will look how do I send response back.
    • FOr this we have @RestController annotation. part of it has @ResponseBody
    • What would happen when we put ResponseBody on a controller?
    • the response from it would be mapped by message convertor to some other format.
    • Here, we use Jackson as message convertor
  • Converts it into JSON and then response back.
    • So, DispatcherServlet will say do the JSON conversion using jackson

Popular Posts

Most Featured Post

GitHub: Squash all commits in PR

  Command Meaning git fetch origin Get the latest origin/master . git reset --soft origin/master Move your branch to match origin/master , b...