Saturday, July 13, 2019

jUnit && Mockito code-driven unit testing framework


Junit – 4, 4++, 5

Test:- it is the validation of functional and nonfunctional requirements before it is shipped to a customer.

Unit testing means performing the sanity check of code.
Sanity check is a basic test to quickly evaluate whether the result of a calculation can possibly be true.
It is a simple check to see whether the produced material is coherent.

Use Case:-

It's a common practice to unit test the code using print statements in the main method or by executing the application.
Neither of them is the correct approach.

Mixing up production code with tests is not a good practice. Testing logic in the production code is a code smell, though it doesn't break the code under the test. However, this increases the complexity of the code and can create severe maintenance problem or cause system failure if anything gets misconfigured.

Print statements or logging statements are executed in the production system and print unnecessary information. They increase execution time and reduce code readability. Also, junk logging information can hide a real problem, for instance, you may overlook a critical deadlock or a hung thread warning because of excessive logging of junk.


Unit testing is a common practice in test-driven development (TDD). TDD is a development approach where the production code is written only to satisfy a test, and the code is refactored to improve its quality. Basically, It offers test-first development.
In TDD, unit tests drive the design.

Java code can be unit tested using a code-driven unit testing framework.

The following are a few of the available code-driven unit testing frameworks for Java:
• SpryTest
• Jtest
• JUnit
• TestNG

JUnit is the most popular and widely used unit testing framework for Java.

Junit – code-driven unit testing framework for java, It is an annotation-based, flexible framework.

Apparently, TestNG is cleaner than JUnit, but JUnit is far more popular than TestNG.
JUnit has a better mocking framework support such as Mockito, which offers a custom JUnit 4 runner.

Exploring annotations
The @Test annotation represents a test.
Any public method can be annotated with the @Test annotation with @Test to make it a test method. There's no need to start the method name with test.

We need data to verify a piece of code. For example, if a method takes a list of students and sorts them based on the marks obtained, then we have to build a list of students to test the method. This is called data setup.

JUnit 4 provides a @Before annotation. If we annotate any public void method of any name with @Before, then that method gets executed before every test execution. Similarly, any method annotated with @After gets executed after each test method execution.

JUnit 4 provides two more annotations:
@BeforeClass and @AfterClass.

They are executed only once per test class. The @BeforeClass and @AfterClass annotations can be used with any public static void methods. The @BeforeClass annotation is executed before the first test and the @AfterClass annotation is executed after the last test. The following example explains the annotation usage and the execution sequence of the annotated methods.

Verifying test conditions with Assertion

Assertion is a tool (a predicate) used to verify a programming assumption (expectation) with an actual outcome of a program implementation; for example, a programmer can expect that the addition of two positive numbers will result in a positive number. So, he or she can write a program to add two numbers and assert the expected result with the actual result.

The org.junit.Assert package provides static overloaded methods to assert expected and actual values for all primitive types, objects, and arrays.

The following are the useful assert methods:

assertTrue(condition)
assertFalse(condition)
assertNull
assertNotNull
assertEquals(string message, object expected, object
actual)
assertEquals(object expected, object actual) := i.equals(j) and not i == j . Hence, only the values are compared, not the references
assertEquals(primitive expected, primitive actual)
assertSame(object expected, object actual) := passes only when the expected object and the actual
object refer to the same memory location.
assertNotSame(object expected, object actual) := fails only when the expected object and the actual object refers to the same memory location.

if the actual value doesn't match the expected value, AssertionError is thrown.

Working with exception handling
an API needs three objects; if any argument is null, then the API should throw an exception. This can be easily tested. If the API doesn't throw an exception, the test will fail.

@Test(expected=RuntimeException.class)
public void exception() {
throw new RuntimeException();}

Exploring the @RunWith annotation


Junit 4++


Ignoring a test

@Test
@Ignore("John's holiday stuff failing")
public void when_today_is_holiday_then_stop_alarm() {
}

Executing tests in order

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestExecutionOrder { ... }

Learning assumptions

Exploring the test suite

To run multiple test cases, JUnit 4 provides Suite.class and the @Suite.SuiteClasses annotation. This annotation takes an array (comma separated) of test classes.

@RunWith(Suite.class)
@Suite.SuiteClasses({ AssertTest.class, TestExecutionOrder.class, Assumption.class })
public class TestSuite {
}

Create a TestSuite class and annotate the class with @RunWith(Suite.class) .
This annotation will force Eclipse to use the suite runner instead of using the built-in runner.

Asserting with assertThat

Monday, May 13, 2019

Angular 7 - designed around the latest JavaScript features.

Development Env.
Install nodejs(javascript engine) and npm(catalog of development pkgs)
$node -v
$npm -v

Install Angular-CLI
$npm i -g @angular/cli

$ng version
Anglar CLI 7.0.1
.
.
.

Install Visual Studio Code(editor) → View → Terminal

Once you have Node.js, NPM, an editor, and a browser, you have enough of a foundation to start the development process.


$mkdir ng7Demo
$cd ng7Demoo
$ng new ng7App

1) would you like to add Angular routing? Y
2) which stylesheet format would you like to use ? Sass

$code .
This will open code file of application

package.json - list of the software packages that are required for a project.
tsconfig.json - TypeScript compiler requires a configuration file to control the kind of JavaScript files that it generates.
index.html - 


Starting Server
$ng serve
OR
$npm start

This command tells npm to run the start script, which starts the TypeScript compiler and the light-weight development HTTP server




________________________________________________________________________

Entry point into the world of Angular :-


1. Preparing the HTML File
index.html

<body>
 <todo-app>Angular placeholder</todo-app>
</body>

</html>

2. Creating a Data Model
model.ts

- ES5
var model = {
 user: "Adam",
 items: [{ action: "Buy Flowers", done: false },
 { action: "Get Shoes", done: false },
 { action: "Collect Tickets", done: true },
 { action: "Call Joe", done: false }]
};

When you save the changes to the file, the TypeScript compiler will detect the change and generate a file called model.js

- ES6

export class Model {
 user;
 items;
 constructor() {
 this.user = "Adam";
 this.items = [new TodoItem("Buy Flowers", false),
new TodoItem("Get Shoes", false),
new TodoItem("Collect Tickets", false),
new TodoItem("Call Joe", false)]
 }
}

export class TodoItem {
 action;
 done;
 constructor(action, done) {
 this.action = action;
 this.done = done;
 }
}

class keyword is used to define types that can be instantiated with the new keyword to create objects that have well-defined data and behavior.

export keyword is used to identity data or types that you want to use elsewhere in the application.

==> TypeScript compiler produced JavaScript code that will work in browsers that don’t implement that feature

"use strict";
var Model = (function () {
 function Model() {
 this.user = "Adam";
 this.items = [new TodoItem("Buy Flowers", false),
 new TodoItem("Get Shoes", false),
 new TodoItem("Collect Tickets", false),
 new TodoItem("Call Joe", false)];
}
 return Model;
}());
exports.Model = Model;

var TodoItem = (function () {
 function TodoItem(action, done) {
 this.action = action;
 this.done = done;
 }
 return TodoItem;
}());
exports.TodoItem = TodoItem;


3. Creating a Template
app.component.html 

a way to display the data values in the model to the user. In Angular, this is done using a template, which is a fragment of HTML that contains instructions that are performed by Angular.

<h3 class="bg-primary p-a-1">{{getName()}}'s To Do List</h3>

Including a data value in a template is done using double braces—{{ and }}—and Angular evaluates whatever you put between the double braces to get the value to display.

The {{ and }} characters are an example of a data binding, which means that they create a relationship between the template and a data value.

In this case, the data binding tells Angular to invoke a function called getName and use the result as the contents of the h3 element.

4. Creating a Component
app.component.ts

An Angular component is responsible for managing a template and providing it with the data and logic it needs. At the moment, I have a data model that contains a user property with the name to display, and I have a template that displays the name by invoking a getName property. What I need is a component to act as the bridge between them.


import { Component } from "@angular/core";
import { Model } from "./model";

@Component({
 selector: "todo-app",
 templateUrl: "app/app.component.html"
})

export class AppComponent {
 model = new Model();
 getName() {
 return this.model.user;
 }
}

import keyword is the counterpart to the export keyword.

decorator - which provides metadata about a class.

@Component decorator,it tells Angular that this is a component. The decorator provides configuration information through its properties, which in the case of @Component includes properties called selector and templateUrl.

selector property specifies a CSS selector that matches the HTML element to which the component will be applied.
templateUrl property is used to tell Angular how to find the component’s template.

class called AppComponent which provide the functionality required to support the data binding in the template. When a new instance of the AppComponent class is created, the model property will be set to a new instance of the Model class and getName function returns the value of the user property defined by the Model object.

5. Creating a Module / Putting the Application Together
app.module.ts

Every application has a root module, which provides Angular with the information that it needs to start the application.

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";

@NgModule({
 imports: [BrowserModule, FormsModule],
 declarations: [AppComponent],
 bootstrap: [AppComponent]
})
export class AppModule { }

6. Entry point into the application
main.ts

Angular applications also need a bootstrap file, which contains the code required to start the application and load the Angular module.

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule); // browser-based applications

code statements in the bootstrap file select the platform that will be used and load the root module, which is the entry point into the application.

7. Running the Application

The browser executed the code in the bootstrap file, which fired up Angular, which in turn processed the HTML document and discovered the todo-app element. 

The selector property used to define the component matches the todo-app element, which allowed Angular to remove the placeholder content and replace it with the component’s template, which was loaded automatically from the app.component.html file. The template was parsed; the {{ and }} data binding was discovered, and the expression it contains was evaluated, calling the getName and displaying the result.

Friday, May 3, 2019

Lambda expressions

1. Lambda expressions are just like functions and they accept parameters just like functions.
2. Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.

An example is java.lang.Runnable.


//Thread Example without lambda using anonymous class
        Runnable r1=new Runnable(){
            public void run(){
                System.out.println("Thread1 is running...");
            }
        };
        Thread t1=new Thread(r1);
        t1.start();
        //Thread Example with lambda  
        Runnable r2=()->{
                System.out.println("Thread2 is running...");
        };
        Thread t2=new Thread(r2);
        t2.start();

Java Lambda Expression Syntax
(argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.

_____________________________________________________________________

@FunctionalInterface  //It is optional
interface FuncInterface1
{
    // An abstract function
    void abstractFun();

    // A non-abstract (or default) function
    default void normalFun()
    {
       System.out.println("Hello");
    }
}

@FunctionalInterface
interface FuncInterface2
{
    // An abstract function
    void abstractFun(int x);

    // A non-abstract (or default) function
    default void normalFun()
    {
       System.out.println("Hello");
    }
}

interface Addable{
    int add(int a,int b);
}

class Test
{
    public static void main(String args[])
    {
        // lambda expression to implement above
        // functional interface.
        FuncInterface1 fobj1 = ()->{ System.out.println("lamda"); }; //No Parameter

        // This calls above lambda expression.
        fobj1.abstractFun();

 FuncInterface2 fobj2 = (int x)->{ System.out.println("lamda " + 2*x); }; //One Parameter
        fobj2.abstractFun(5);

        Addable ad1=(a,b)->(a+b);  // Multiple parameters
        System.out.println(ad1.add(10,20));
       
        Addable ad2=(int a,int b)->(a+b);  // Multiple parameters with data type
        System.out.println(ad2.add(100,200));

    }
}

Wednesday, May 1, 2019

Inheritance vs Composition

Inheritance is an "is-a" relationship. Composition is a "has-a".

Example: Car is a Automobile and Car has a Engine.

class Engine {} // The Engine class.

class Automobile {} // Automobile class which is parent to Car class.

class Car extends Automobile { // Car class extends Automobile class.
  private Engine engine; // Car class has an instance of Engine class as its member.
}

**************************************************************************

public class X{ 
   public void do(){ 
   } 

public class Y extends X{
   public void work(){ 
       do(); 
   }
}

1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature

public class X{ 
   public void do(){ 
   }
public int work(){
} 
}  

Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.

How does composition solves this issue?

Lets see by revising the same example

public class X{
    public void do(){
    }
}

public class Y{
    X x = new X();    
    public void work(){    
        x.do();
    }
}

Here we are creating reference of X class in Y class and invoking method of X class. Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.

2) Second very good advantage of composition in that it provides method calling flexibility, for example :

class X implements R
{}
class Y implements R
{}

public class Test{    
    R r;    
}
In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance.

3) Another great advantage : Unit testing

public class X {
    public void do(){
    }
}

public class Y {
    X x = new X();    
    public void work(){    
        x.do();    
    }    
}
In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.

4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.

Lets take an example to understand this :

public class Transaction {
    Banking b;
    public static void main(String a[])    
    {    
        b = new Deposit();    
        if(b.deposit()){    
            b = new Credit();
            c.credit();    
        }
    }
}
Good to know :
composition is easily achieved at runtime while inheritance provides its features at compile time.

So make it a habit of always preferring composition over inheritance for various above reasons.

Summary:-
Composition - has-a relationship between objects.
Inheritance - is-a relationship between classes.

Composition - Composing object holds a reference to composing classes and hence relationship is loosely bound.
Inheritance - Derived object carries the base class definition in itself and hence its tightly bound.

Composition - Used in Dependency Injection
Inheritance - Used in Runtime Polymorphism

Composition - Single class objects can be composed within multiple classes.
Inheritance - Single class can only inherit 1 Class.

Composition - Its the relationship between objects.
Inheritance - Its the relationship between classes.

Saturday, October 21, 2017

Javascript

Functions - may or may not return a value.

function declaration

function function_name(){
 // statements
};

var c = function_name();
console.log(c);

function expression

var function_name = function(){
 //statements
};

var c = function_name();
console.log(c);

Methods - when function is an object's property

var calc = {

add : function(a,b) {
          return a+b
          },

sub : function(a,b){
          return a-b
          }
}

calc => object
add,sub => method

calc.add(1,2);
calc.sub(3,2);

Constructors - when you add new keyword before a function and call it, it becomes a constructor that create instances.

function fruit(){
  var name,family;
  this.getName = function(){
      return name;
  };
  this.setName = function(value){
      name=value;
  };
}


var apple = new fruit();
apple.setName("Malus");
console.log(apple.getName());

function as a parameter

function f1(val){
    return val.toUpperCase();
}

function f2(val,passFunc){
    console.log(passFunc(val));
}

f2("small",f1);
// string, reference


Scope
global/public
local/private

global variable
- place a var statement outside any function
- omit var statement
local variable
- variables declared within a function

this parameter
refers to an object that's implicitly associated with function invocation

invocation as a function
- 'this' is bound to global object(window)
invocation as a method
- 'this' is bound to object
invocation as a constructor

Create JavaScript Object
object literal => similar to JSON format
var author ={
// variables
 firstName : "Megha",
 lastName : "Dureja",
 book : {
            title : "JS",
            pages : "172"
 }
// method
 meetingRoom : function(roomId){
    console.log("BookedRoom");
 }
};

console.log(author.lastName);
console.log(author.book.title);

object constructor
var author = new Object();

function constructor

prototype

function/prototype combination

singleton


Variable / Object

variable - container for data value
var car = "Polo";

Object - container for many value and methods to perform action
 <script>
var car = {
 type : "Polo",
 model : "500",
 color : "white"
 fullName : function(){
 return this.type + "" + this.model + "" +this.color;
 }
};
</script>


Hadoop Ecosystem

Hadoop Ecosystem = HDFS + MapReduce + Tools(Hive,Pig,HBase,Zookeeper,Flume,Sqoop,Oozie,Mahout)

Three modes
Local standalone mode - single JVM
pseudo distributed mode - separate JVM
fully distributed mode - multiple JVM

Hadoop Components
Namenode
Datanode
Secondary Namenode
JobTracker
TaskTracker

Configuration files
core-site.xml => location of namenode
hdfs-site.xml => replication factor
mapred-site.xml => location of jobtracker

hadoop dfs -ls
dfs -copyFromLocal
dfs put
dfs -cat
dfs -get

Wednesday, September 27, 2017

Web Server vs Web Container vs Application Server

Apache software foundation produces two types of web servers.
Apache HTTP used for static content that can also be equipped with modules to serve dynamic content (e.g. PHP, Ruby), as well as
Apache Tomcat which is a web-container (i.e. application server) used for serving dynamic content written in Java.

Once you've confirmed the Apache version, you should check the web server's modules. Modules serve as add-ons to support extra features that can include things like CGI, Secure Socket Layer (SSL), Virtual Hosting, as well as the processing of web applications written in just about any programming language. Inclusively, there are certain modules that can be helpful for increasing performance.

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...