MainMenu

Home Java Overview Maven Tutorials

Monday, 21 February 2022

Loose Coupling and Tight Coupling in Java with example

Loose Coupling and Tight Coupling in Java with example



Hello Friends,

This article will describe the concept of tight and loose coupling in java.



Coupling :- Degree of dependency of Class A on Class B.
How often do changes in one class force changes in another class.


Tight Coupling :-
Two classes often change together If class A knows more than it should about the way in which class B was implemented, then A and B are tightly coupled.


Loose Coupling :-
Reducing the dependencies of a class that uses the different classes directly.
If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled.


Example of Tight coupling
class A1
{
A1(int x , int y)
{
System.out.println("sum is " + (x+y));
}
void sam()
{
System.out.println("i am method of class A");
}
}
class B extends A1
{
B(int x, int y)
//have to add this constructor other wise while creating the object , compile time error will appear. {
super(x, y);
}
void sam()
{
System.out.println("i am method of class B");
}
}
public class Coupling
{
public static void main(String args[])
{
B obj = new B(7, 8);
obj.sam();
}
}


Example of loose coupling
interface mycoup
{
void sample();
}
class A1 implements mycoup
{
A1(int x , int y)
{
System.out.println("sum is " + (x+y));
}
@Override
public void sample()
{
System.out.println("i am method of class A");
}
}
class B implements mycoup
{
public void sample()
{
System.out.println("i am method of class B");
}
}
public class Coupling
{
public static void main(String args[])
{
B obj = new B();
obj.sample();
A1 obj1 = new A1(3, 7);
obj1.sample();
}
}

Output:-
i am method of class B
sum is 10
i am method of class A

Saturday, 12 February 2022

Upload Operation in Selenium testing the post

How to upload the file using selenium

Click Here to navigate on practice page



Hello Friends, In this tutorial we will learn how to perform upload operation in selenium.
We can perform the upload operation in selenium by two ways :
1). First by SendKeys() method.
2). Second by using the robot class.
First Method :
Precondition : Element should be input and type should be "file", as shown below :



Now we just need to locate the element and just use the method sendKeys() and in sendKeys() method we will pass the path of that file.
Syntax :-
driver.findElement(By.xpath("path of element")).sendKeys("path on file");

Here is sample code :-

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Uploadfile
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
/*FirefoxOptions foptions = new FirefoxOptions();
foptions.setCapability("marionette", false);
driver = new FirefoxDriver(foptions);*/
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com/p/this-webpage-is-designed-for-selenium.html");
Thread.sleep(3000);
}
@Test
public void h()
{
//Remember element should be input and type should be "file"
driver.findElement(By.xpath(".//*[@id='post-body-2064404811754288590']/form[1]/input[1]")).sendKeys("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
}
}





Second Method : By using Robot Class:-
What is Robot class ?
"Basically robot class will simulate the Keyboard and mouse actions."
Steps :-
1). First Copy the file path.
2).Paste the file path in popup window
3).Press Enter button.

by robot class we can perform CTRL + C operation by below methods as :-
StringSelection ss = new StringSelection("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

by robot class we can perform CTRL + V operation as below :-
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);



by robot class we can press enter key as below :-
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Here is sample code :-

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Uploadfile
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
/*FirefoxOptions foptions = new FirefoxOptions();
foptions.setCapability("marionette", false);
driver = new FirefoxDriver(foptions);*/
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com/p/this-webpage-is-designed-for-selenium.html");
Thread.sleep(3000);
}
@Test
public void h() throws AWTException
{
driver.findElement(By.xpath(".//*[@id='post-body-2064404811754288590']/form[1]/input[1]")).click();
Robot robot = new Robot();
robot.setAutoDelay(2000);
StringSelection ss = new StringSelection("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
robot.setAutoDelay(2000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}

Monday, 19 April 2021

Constructor Chaining In java

What is Constructor chaining in JAVA



Definition :-

The process of invoking a sequence of constructors upon initialization of a class object is called constructor chaining.
Constructor chaining is useful when you want to invoke multiple constructors, one after another, by initializing only one instance.

Constructor chaining can be done in two ways:
Within same class: It can be done using this() keyword for constructors in same class
From base class: by using super() keyword to call constructor from the base class.



package ChandanPack1;

class A
{
A()
{
this(0);
System.out.println("I am inside A class constructor");
}
A(int x)
{
this(2, 4);
System.out.println("Superclass second constructor" + " " +x);
}
A(int l, int m)
{
System.out.println("multiply is " + " " + (l*m));
}
}

public class BajiPractice extends A
{
BajiPractice()
{
this(10);
System.out.println("i am inside first constructor");
}
BajiPractice(int x)
{
this(2, 80);
System.out.println("number is:->" + " "+ x);
}
BajiPractice(int a, int b)
{
super();
System.out.println("the sum is" + " " +(a+b));
}
public static void main(String args[])
{
System.out.println("constructor chaining started");
BajiPractice obj = new BajiPractice();
}
}



Output:- constructor chaining started
multiply is 8
Superclass second constructor 0
I am inside A class constructor
the sum is 82
number is:-> 10
i am inside first constructor

Sunday, 11 April 2021

Contract Testing Overview

Contract Testing in API







Microservices :-

Microservices is an architectural design for building a distributed application using containers. Microservices get their name because each function of the application operates as an independent service. This architecture allows for each service to scale or update without disrupting other services in the application.



Contract Testing :- Contract testing is a way to ensure that services (such as an API provider and a client) can communicate with each other. Without contract testing, the only way to know that services can communicate is by using expensive and brittle integration tests.

A service consumer and a service provider interact with each other based on some protocol or rules. This set of rules of communication between two services is called Contract and the process of testing the communication between the two services based on this Contract is called Contract Testing.




Wednesday, 31 March 2021

API Testing Interview Questions

API Testing Interview Questions







What are Web Services?

A web Service can be defined by the following ways :-

1). Is a client server application or application component for communication.
2). Method of communication between two devices over network.
3). Is a software system for interoperable machine to machine communication.
4). Is a collection of standards or protocols for exchanging information between two devices of application.

What all challenges are included under API Testing?

API Documentation
Access to DB
Authorizarion Overhead

What is the difference between PUT and POST methods ?

Post :- Creating a new object on the server
Put :- Update the object in server with new table

What are Commonly used HTTP methods?


GET :- It enables you to retrieve data from a server
POST :- It enables you to add data to an existing file or resource in a server
PUT :- It lets you replace an existing file or resource in a server
Delete :- It lets you delete data from a server

List out few Authentication Technique used in API's?


Session/Cookie based Authentication
Basic Authentication
Digest Authentication
OAuth

What is Rest API?


REST stands for Representational State Transfer. It is set of functions helping developers in performing requests and receive responses. Interaction is made through HTTP protocol in REST API.

What exactly needs to verify in API testing?

In API testing, we send a request to API with the known data and then analysis the response.
1). We will verify the accuracy of the data.
2). Will see the HTTP status code.
3). We will see the response time.
4). Error codes in case API returns any errors.
5). Authorization would be check.
6). Non functional testing such as performance testing, security testing.

What are path parameters and Query parameters for below API Request URL

/ for path parameter
? is for Query parameter
for example http://way2testing.com/tutorialorder/1122369?location=GHN

so here /1122369 is path parameter
and ? location is Query parameter also in In General Query Parameter is constructed at the end of URL.

Whar are the core componenets of a HTTP request?

HTTP Request methods like PUT, POST, Delete.
Base Uniform Resource identifier (URI)
Resources and Parameters
Request Header, which carries metadata(a key-value pairs) for the HTTP Request message.
Request Body, which indicates the message content or resource representation.

What could be the HTTP method for below API Scenario? Answer if it is GET or POST.

Scenario :- An API which has Endpoint, Parameter, Headers, cookies and Payload.
Answer :- It is a POST request because it have Payload

What are the differences between API Testing and UI testing?

UI(User Interface) testing means the testing of the graphical user interface. The focus of UI testing is on the look and feel of the application. In user interface testing the main focus is on how user can interact with app elements such as images, fonts, layout etc. are checked.
API testing allows the communication between two software systems. API testing works on backend also known as backend testing.

What protocols is used by the RESTFUL web services?

RESTFUL web services uses the HTTP protocol. They use the HTTP Protocol as a medium of communication between the client and the server.

What are Soap webservices?

SOAP stands for Simple Object Access Protocol. It is an XML based messaging protocol. It helps in exchanging information among computers.

How do we Represent A resource in REST

Using HTTP methods

Can you use POST request instead of PUT to create a resource?

Yes, we can, because POST is Super set of all other HTTP methods except GET.

What do you understand by payload in restful Web Services?

Payload/Body is the secured input data which is sent to API to process the request. Payload is generally represented in JSON format in Rest API's.

What is Rest Assured.

It is Java Library which can automate REST API's.

How would we define API details in Rest Assured Automation?

we shall define all the request details and send it to server in GIVEN, WHEN & THEN methods.

What is Json serialization & Deserialization in Rest Assured.

Serialization in Rest Assured context is a process of converting a Java Object into Request body(payload).

Rest Assured also supports deserialization by converting Response body back to java Object.

List out few common Json Parsing Techniques used in Rest Assured Automation?

Json Path Deserialization of Json using POJO classes.

How would you send attachments to API using Rest Assured Test?

Using MultiPart Method.

Different Status Code & their description :-

200 OK The request was successfully completed

201 Created A new Resources was successfully created.

400 Bad Request The request was invalid

401 unauthorized The request did not include an authentication token or the authentication token was expired

403 forbidden The client did not have permission to access the requested resource

404 Not Found The requested resource was not found

405 Method not allowed The HTTP methods in the request was not supported by the resource.

409 Conflict The request could not be completed due to a conflict.

500 Internal server Error The request was not completed due to an internal error on server side.

503 Service Unavailable The server was unavailable.

Monday, 15 March 2021

Reflection In Java



Reflection in java





Java Reflection :- In Java, reflection allows us to inspect and manipulate classes, interfaces, constructors, methods, and fields at run time.

There is a class in Java named Class that keeps all the information about objects and classes at runtime.
The object of Class can be used to perform reflection.

What is the Java Reflection API?
1. Class Manipulator.
2. Used to manipulate classes and everything in a class.
3. can slow down a program because the JVM can't optimize the code.
4. Can't be used with applets.
5. Should be used sparingly.

Reflection of Java Classes

In order to reflect a Java class, we first need to create an object of Class.
And, using the object we can call various methods to get information about methods, fields, and constructors present in a class.

There exists three ways to create objects of Class:
1. Using forName() method
2. Using getClass() method
3. Using .class extension



Example 1:-
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.Class;

class vehicle
{
public void g()
{
System.out.println("I am Inside vehicle");
}
}
class car extends vehicle
{
public int x ;
public String name;
car()
{
System.out.println("i am inside constructor");
}
car(int x, int y)
{
System.out.println("Sum is " + (x+y));
}
public void j()
{
System.out.println("I am Inside car");
}
}
public class TestCsc3
{
public static void main(String args[]) throws ClassNotFoundException
{
car cr = new car();
Class cobj = cr.getClass();
TestCsc3 tc = new TestCsc3();
Class cobj2 = tc.getClass();
//get the name of class
String classname = cobj.getName();
System.out.println("Name of the class is " + classname);
//get super class
Class scla = cobj.getSuperclass();
System.out.println("Name of super class is " + scla.getName());
//get the constructor of the class
Constructor[] consname = cobj.getDeclaredConstructors();
for(Constructor c : consname)
{
System.out.println("Constructor name is :" +c.getName());
}
//get the modifier of the class
int modi = cobj2.getModifiers();
String modif = Modifier.toString(modi);
System.out.println("Modifier of class is " + (modif));
//get all the methods of the class
Method[] mth = cobj.getMethods();
for(Method m : mth)
{
System.out.println("Name is the methods" + m.getName());
}
//get declared methods of the class
Method[] mth2 = cobj.getDeclaredMethods();
for(Method m2 : mth2)
{
System.out.println("Name is the declared method is :-> " + m2.getName());
}
//get fields of class
Field[] fld = cobj.getDeclaredFields();
for(Field f : fld)
{
System.out.println("Name of the fiels is " + f.getName());
}
}
}

Output :-

i am inside constructor
Name of the class is practice.car
Name of super class is practice.vehicle
Constructor name is :practice.car
Constructor name is :practice.car
Modifier of class is public
Name is the methods j
Name is the methods g
Name is the methodswait
Name is the methodswait
Name is the methodswait
Name is the methodsequals
Name is the methodstoString
Name is the methodshashCode
Name is the methodsgetClass
Name is the methodsnotify
Name is the methodsnotifyAll
Name is the declared method is :-> j
Name of the fiels is x
Name of the fiels is name
-------------------------------------------------------------------------------------
Example 2:-

import java.lang.Class;
import java.lang.*;
class pent
{
}
public class Reflection2
{
public static void main(String[] args) throws ClassNotFoundException
{
Class c = Class.forName("practice.pent");
System.out.println("the name is class " + c.getName());
}
}

Output :-
the name is class practice.pent

Wednesday, 17 February 2021

Blackbox Testing Technique




Hello Friends,
Here we will learn the black box testing test case design technique :-
Decision Table Testing :-
1). Decision Table captures system requirements that contain logical conditions.
2). The specification are analyzed, and conditions and actions of the system are identified in a tabular form.
3). The input conditions and actions are most often stated in a way that they must be true or false.

Decision table technique is one of the widely used case design techniques for black box testing. This is a systematic approach where various input combinations and their respective system behavior are captured in a tabular form.
That's why it is also known as a cause-effect table. This technique is used to pick the test cases in a systematic manner; it saves the testing time and gives good coverage to the testing area of the software application.
Decision table technique is appropriate for the functions that have a logical relationship between two and more than two inputs.



Decision Table Example :

State Transition Diagram Testing technique :-
A state diagram – also known as state chart, state machine diagram or state transition diagram – visualises a sequence of states that an object can assume in its lifecycle. It is used to describe the behavior of a system, subsystem, component, or class.
state-transition diagram (STD) A diagram that indicates the possible states of a finite-state automaton and the allowable transitions between such states. ... Each one depicts the states, transitions, and event(s) that can cause each transition.





Orthogonal Array Testing
Orthogonal array testing is a systematic and statistical way of a black box testing technique used when number of inputs to the application under test is small but too complex for an exhaustive testing.

Orthogonal Array Testing Characteristics:
1)OAT, is a systematic and statistical approach to pairwise interactions.
2)Executing a well-defined and a precise test is likely to uncover most of the defects.
3)100% Orthogonal Array Testing implies 100% pairwise testing.

Consider a system which has three parameters {country; product; sales person} and each of them has three values. To test all the possible combinations of these parameters (i.e. exhaustive testing) we will need a set of 33 = 27 test cases. But instead of testing the system for each combination of parameters, we can use an orthogonal array to select only a subset of these combinations. Using orthogonal array testing, we can maximize the test coverage while minimizing the number of test cases to consider. We here assume that the pair that maximizes interaction between the parameters will have more defects and that the technique works.

Orthogonal array
Test case ↓ Country Product Salesperson
TC-1 DE Notebook Charlie
TC-2 DE Desktop Bob
TC-3 DE Mouse Alice
TC-4 US Notebook Bob
TC-5 US Desktop Alice
TC-6 US Mouse Charlie
TC-7 GB Notebook Alice
TC-8 GB Desktop Charlie
TC-9 GB Mouse Bob