In the below code we are going to mock the List Interface and override the method behaviour of List Methods
Methods mocked

  1. get(index)
  2. size()
  3. exception

ListTest.java

package com.mugil.org;

import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.junit.Assert.assertEquals;

public class ListTest {
    List arrEmployee;

    @Before
    public void init(){
        arrEmployee = mock(List.class);
    }

    @Test
    public void ListMock_SizeMethod(){
        when(arrEmployee.size()).thenReturn(3);
        assertEquals(3, arrEmployee.size());
    }

    @Test
    public void ListMock_GetMethod(){
        when(arrEmployee.get(0)).thenReturn("Employee1");
        when(arrEmployee.get(1)).thenReturn("Employee2");
        when(arrEmployee.get(2)).thenReturn("Employee3");

        assertEquals("Employee2", arrEmployee.get(1));
        assertNotEquals(null, arrEmployee.get(2));
    }

    @Test(expected = RuntimeException.class)
    public void ListMock_ThrowException(){
        when(arrEmployee.get(anyInt())).thenThrow(new RuntimeException());
        arrEmployee.get(1);
    }
}

Below is a simple class which uses stub for Testing

  1. Below is a simple business implementation class which EmployeeDetailsImpl which uses EmployeeService API methods
  2. Now to test EmployeeDetailsImpl we need to substitude the methods in service class with stub methods for which we create EmployeeServiceStub
  3. EmployeeServiceStub is a stub class which implements the EmployeeService and provide method definitions
  4. EmployeeDetailsImplTest is the test class for EmployeeDetailsImpl which performs the unittest for methods in EmployeeDetailsImpl

EmployeeService.java

 
import java.util.List;

public interface EmployeeService {
    public List<String> GetEmployeeDetails();
}

EmployeeDetailsImpl.java

 
import com.mugil.org.api.EmployeeService;

import java.util.List;

public class EmployeeDetailsImpl {
    EmployeeService employeeService;

    public EmployeeDetailsImpl(EmployeeService pEmployeeService){
        this.employeeService = pEmployeeService;
    }

    public List<String> getEmployeeList(){
        List<String> arrEmp = this.employeeService.GetEmployeeDetails();
        return arrEmp;
    }
}

EmployeeServiceStub.java

 
import java.util.Arrays;
import java.util.List;

public class EmployeeServiceStub  implements  EmployeeService{

    @Override
    public List<String> GetEmployeeDetails() {
        return Arrays.asList("Mugil", "Mani", "Vinu");
    }
}

EmployeeDetailsImplTest.java

 
import com.mugil.org.api.EmployeeServiceStub;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class EmployeeDetailsImplTest {
    @Test
    public void getEmployeeList_success(){
        EmployeeServiceStub employeeService = new  EmployeeServiceStub();
        EmployeeDetailsImpl employeeDetailsImpl = new EmployeeDetailsImpl(employeeService);
        assertEquals(3, employeeDetailsImpl.getEmployeeList().size());
    }
}

Dis-advantage of the above implementation

  1. In the above implementation when ever new method is added to the API interface, it should be added to the EmployeeServiceStub which implements EmployeeService
  2. EmployeeServiceStub is extra java file which should be taken care, incase there are multiple services used in class multiple service stub needs to be created

Replacing stub with mocks
In the below code, the same stub service(EmployeeServiceStub.java) is replaced with mock class and its methods are replaced using when and return.This prevents the need for another class

EmployeeDetailsImplTest.java

 
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class EmployeeDetailsImplTest {
    @Test
    public void getEmployeeList_success(){
     
        //Replacement code for Stub class
        EmployeeService employeeService = mock(EmployeeService.class);
        when(employeeService.GetEmployeeDetails()).thenReturn(Arrays.asList("Mugil", "Mani", "Vinu"));

        EmployeeDetailsImpl employeeDetailsImpl = new EmployeeDetailsImpl(employeeService);
        assertEquals(3, employeeDetailsImpl.getEmployeeList().size());
    }
}

Parts of OpenAPI 3.0 Specification
Info and Components are important parts of API Definition

  1. Info – Provides Name, Description and Developers information of API
  2. Servers – Provides server information and various environment URL of API
  3. Security – Provides details about how API is secured, API keys, Authorization information
  4. Paths – Details about API Endpoints
  5. Tags and extenaldocs – Tags that could be grouped for API operations
  6. Components – Set of reusable objects which could be used during API definition

Mocking Dependency Injection Objects
There may be times where the service would be injected into the component using constructor by DI. In such a case while creating a component instance for test class we could end up with a problem. To answer this we pass mock objects as alternate to constructors

add.employee.component.ts

export class EmployeeComponent implements OnInit {
 .
 .
  constructor(private objEmpserviceService : EmpserviceService) {
  }

  checkForAuthentication(): string {
    if(this.objEmpserviceService.authenticateEmp('Admin')){
      return "You are allowed to Edit";
    }
    return "You are Not allowed to Edit";
  }
 .
 .

Two Methods to Answer this Problem
Method 1 : If you are not going to call the mockedObject methods

To address this the injected object using dependency injection we use providers. Providers provide mockedobject to constructor instead of real object like below

add.employee.component.spec.ts

let mockEmpserviceService:EmpserviceService;

beforeEach(async(() => {
    mockEmpserviceService = jasmine.createSpyObj(['authenticateEmp', 'addEmployee', 'deleteEmployee']); 

    TestBed.configureTestingModule({
      .
      declarations: [ EmployeeComponent ],
      providers : [ 
                   {provide:EmpserviceService, useValue:mockEmpserviceService}
                  ]
      .
      .
    }).compileComponents();
  }));
  • Now in the above code we have mocked the service using mockEmpserviceService and providing a list of methods. But the returnType is still missing. So this could be used only to check if the actual method under test is called without using callThrough which in turn calls the method in mockedObject.
     .
     it('Check for Service Method', ()=>{
        spyOn(component, 'checkForAuthentication');
       
        let auth = component.checkForAuthentication();
        (or)
        const btnAddEmp = fixture.debugElement.query(By.css("#btnAddEmp"));
        btnAddEmp.triggerEventHandler('click', {});
        fixture.detectChanges();
         
        expect(auth).toHaveCalled();
     });
     .
    

    Method 2 : If you are going to call the mocked object methods then in such case the return type of the method should be defined.The same code can be done using actual EmpserviceService in provider and using spyOn inside its block to define the returnType of service method.

    let empService: EmpserviceService;
    
    beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ EmployeeComponent],
          providers : [ EmpserviceService],
          imports: [HttpClientTestingModule]
        })
        .compileComponents();
    
        empService = Testbed.inject(EmpserviceService);
      }));
    
      fit('Check for Service Method', ()=>{  
        //Mocking authenticateEmp to return true as if it is called    
        spyOn(empService, 'authenticateEmp').withArgs('Admin').and.returnValue(true);      
        spyOn(component, 'checkForAuthentication').and.callThrough();
        let auth = component.checkForAuthentication();
        expect(auth).toBe('You are allowed to Edit');
      })
    

    In the above code, checkForAuthentication calls authenticateEmp in empService since it does callThrough.

    Note:Even now the control doesnt goes through empService. It would be called and returnvalue would be sent back.

  • Using spyOn with different Options

    1. Using spyon with callThrough would make the call to actual service
    2. spyOn with returnValue returns the value specified without making call to real function
    3. spyOn withArgs does the same but takes arguments incase there is somelogic needs to change when using along callthrough
    4. spyOn callFake would run anonymous function withits own logic rather than calling original function to act on logic
    spyOn(empService, 'authenticateEmp').withArgs('Admin').and.callThrough();
    
    spyOn(empService, 'authenticateEmp').and.returnValue(true);
    
    spyOn(empService, 'authenticateEmp').withArgs('Admin').and.returnValue(true);
    
    spyOn(empService, 'authenticateEmp').and.callFake(function(name, args){
       return true;
    });
    

    What is difference between returnValue and callFake?
    If we just want a return value when a service method is called then we can use any of and.callFake or and.returnValue. Lets take below example

    component file:

    @Component(...)
    export class DependencyComponent {
      constructor(private service: RandomService){....}
      .....
      sampleMethod() {
       return this.service.randomMethod();
      }
      .....
    }
    

    unit test case for above component:

    it('test callFake vs returnValue', () => {
      let randomService= new RandomService();
      let component = new DependencyComponent(randomService);
      spyOn(randomService, 'randomMethod').and.callFake(() => 4)
      expect(component.sampleMethod()).toBe(4)
      spyOn(randomService, 'randomMethod').and.returnValue(10);
      expect(component.sampleMethod()).toBe(10)
    })
    

    in above case both the ways are correct.

    Suppose we are passing a parameter to service method to perform its logic then in that case we have to use and.callFake((param) => {…}). Here param parameter will be the argument passed to the spied method.

    component file:

    @Component(...)
    export class DependencyComponent {
      constructor(private service: RandomService){....}
      .....
      sampleMethod(val) {
      return this.service.randomMethod(val);
      }
      .....
    }
    

    unit test case for above component:

    it('test callFake vs returnValue', () => {
      let randomService= new RandomService();
      let component = new DependencyComponent(randomService);
      spyOn(randomService, 'randomMethod').and.callFake((param) => param+4)
      expect(component.sampleMethod(4)).toBe(8);
      expect(component.sampleMethod(12)).toBe(16)
    })
    

    when component.sampleMethod(4) is executed it will call this.service.randomMethod(4). As randomMethod() is being spied using and.callFake therefore 4 will be passed as argument of call back function of and.callFake.

    One obvious question is can i use returnValue instead of callFake? You can still use but you need to define multiple returnValue methods based on total arguments needs to be tested.

    Before start testing method in components we initialize few things as below

    1. beforeEach method helps in initializing the values needed for testing
    2. describe are similar to JUnit class and it are similar to junit class methods which tests particular method in src code
    3. TestBed is needed while testing both component and html.You need to configure the TestBed before each test, adding any components, modules and services you need for the test. It’s just like configuring an regular @NgModule from scratch, but you just add what you need.
      import { async, TestBed } from '@angular/core/testing';
      
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ AppComponent ],
          providers: [],
          imports: []
        })
        .compileComponents();
      }));
      
    4. Using TestBed.createComponent create component instance returns componentFixture Interface. componentFixture is a wrapper over component with additional methods needed for testing. fixture.componentInstance returns instance of component.
      beforeEach(() => {
      .
      //Returns Component Fixture
      let fixture = TestBed.createComponent(EmployeeComponent);
      
      //Get Instance of Component
      component = fixture.componentInstance;
      .
      .
      });
      
    5. fixture.detectChanges() would allow to check for change in DOM elements before expect or whenever it is referenced for value
    6. DebugElement, an interface which wraps native element instead of HTML element in idle scenario
    7. schemas:[NO_ERRORS_SCHEMAS] lets angular testing module to ignore unknown tags in html during testing. Suppose you have used router tags in html
      and angular could not recognize the router tag since routerTestingModule is not imported you can use this tag as below to avoid errors.

      beforeEach(() => {
           TestBed.configureTestingModule({
            declarations: [ EmployeeComponent]
            schemas:[NO_ERRORS_SCHEMAS]
           }).compileComponents();
      
          //Testbed to create fixture for component
          fixture = TestBed.createComponent(EmployeeComponent);
      
          //Using fixture to create component and service 
          component = fixture.componentInstance;
          empService = TestBed.inject(EmpserviceService);    
       });
      
      

    Simple testing with matchers

    1. toBeTruthy tells the component is created successfully
    2. toBe checks for equality of value
    3. toEqual method does object comparison
    4. toContain method checks whether value is available in array
    fit('Simple component testing', ()=>{
      //Checks whether component has been created
      expect(component).toBeTruthy();
    
      //Checks whether value returned by function are same
      expect(component.getGender(true)).toBe('Male');
    
      //Checks objects are equal and array contain that element
      var Names = ['Name1', 'Name2', 'Name3'];
      expect(Names).toEqual(['Name1', 'Name2', 'Name3']);
      expect(Names).toContain('Name2');
    });
    

    Checking DOM Elements

    1. nativeElement – provides the access to DOM element.This is same as Javascript DOM Element we use for DOM Manipulation.Using nativeElement you can
      access all the API methods provided vy Javascript for DOM manipulation like QuerySelector
    2. fixture.detectChanges() – updates the DOM Element after setting the value from testing component. This is similar to refresh once the component value is set the html should be refreshed.
    3. debugElement– debugElement is similar to nativeElement which has wrapper with some additional methods.It has query, queryAll, queryNode methods
      debugElement inturn calls nativeElement to get the values.fixture.debugElement returns the root debugElement from which we query for the nativeElement.

      .
      .
      fixture.debugElement.query(By.css('a')).nativeElement.textContent)
      fixture.debugElement.query(By.css('#ContactUsId')).nativeElement.textContent)
      fixture.debugElement.query(By.css('.ContactUsId')).nativeElement.textContent)
      .
      .
      .
      
    4. The below statement end up the same anchor tag
      .
      
      fixture.debugElement.query(By.css('a')).nativeElement.textContent)
      fixture.nativeElement.querySelector('a').textContent
      .
      
    1. How to Execute and Disable particular testgroup or testcase in jasmine?
      //Disable particular test group and case
      xDescribe -  @ignore testgroup
      xit - @ignore testcase
      
      //Enable particular test group and case
      fdescribe - Enable Particular Test Group
      fit - Enable Particular Test Case
      
    2. What is Arrange-Act-Assert Pattern
      • Arrange – Creating Object, Initilizing and Mocking Data
      • Act – Act on your unit testcase, execute necessary functionality and methods to be unit tested
      • Assert – Verifying code functionality is given output as expected
    3. What is difference between toBe vs toEqual?
      toBe compares value where as toEqual compares object.toEqual performs deep copy comparison.
    4. Difference between spyOn – returnValue and callFake?
      If we just want a return value when a service method is called then we can use any of and.callFake or and.returnValue. But incase if the service method takes
      some argument and the output of service method changes based on the argument, we use callFake with output logic in callback function. Though the same could be done
      using withargs in spyOn it requires redeclaring of multiple spyOn for multiple arguments.
    5. debugElement vs nativeElement
      NativeElement provides exactlty same API methods provided by Javascript for DOM Manipulation.So whatever methods was available while working in Javascript, the same methods would be available by using instance of nativeElement. debugElement, on the other hand, is a wrapper over native element with some additional methods. Using debugElement you could access rootElement which inturn calls nativeElement to get handle of DOM object. In otherwords debugElement is again going to call nativeElement to access the DOM objects. The additional advantage of using debugElement is accessing directive and component instance which is not possible in nativeElement.
    
    	

    Angular 6 – NullInjectorError: No provider for HttpClient in unit tests
    If you don’t import HttpClientModule (or HttpClientTestingModule) there, HttpClient won’t work because Angular doesn’t know about it. It doesn’t matter that you added HttpClientModule to, say, AppModule. It needs to be in TestBed.configureTestingModule.

    import { TestBed } from '@angular/core/testing';
    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
    import {HttpClientModule} from '@angular/common/http';
    
    describe('myService', () => {
    .
    .
    .
    });
    

    Any checkout that is not the name of one of your branches will get you a detached HEAD.

    The above scenario could be reproduced as below

    1. lists the remote branches
      git branch -r
          origin/Feature/f1234
          origin/master
      
    2. I want to checkout one locally, so I cut paste:
      git checkout origin/Feature/f1234
      
    3. Detached HEAD state
      You are in 'detached HEAD' state. [...])
      

    Solution #1:
    Do not include origin/ at the front of my branch spec when checking it out:

    git checkout Feature/f1234
    

    Solution #2:
    Add -b parameter which creates a local branch from the remote

    git checkout -b origin/Feature/f1234
    git checkout -b Feature/f1234  #it will fall back to origin automatically
    

    But, you have started making changes in the detached branch and you encounter that later. In such case commits will work but changes
    won’t be reflected in branch in remote since it is detached. To address such an issue

    1. commit changes in detached local branch
    2. create a new branch
    3. checkout the branch you are already working so the connection with remote would be again established
    4. Now the new branch created in local contains your changes and checkout will fetch the original remote branch without changes
    5. Do git merge between two and push the code to remote now
    git commit -m "....."
    git branch my-temporary-work
    git checkout master
    git merge my-temporary-work
    
    Posted in git.

    Killing Application by Command

    netstat -aon | find /i "listening"
    netstat -aon | find /i "listening" | find "8080"
    
    taskkill /F / PID ProcessId
    
    i.e. taskkill /F / PID 189
    

    Copy Multiple files from location using command

    #command Line
    for /f "delims=" %i in (C:\list.txt) do (xcopy "%i" "C:\CopyFolder" /i /z /y)
    
    #batch file
    for /f "delims=" %%i in (C:\list.txt) do (xcopy "%%i" "C:\CopyFolder" /i /z /y)