Sunday, October 18, 2015

Mockito Spy

Org.mockito.Spy
Now here comes the situation, the Employee class has one method, and when that method will be called not mockingly but really and call will return the value, we have to use that value to test our real method.

Did you get anything out of my above sentence, if no then read below:
Our Employee.getSummary() method requires address, which can’t be mocked or it requires to call real getTotalMarks() method of Employee class to supply marks during testing.
So what do you want here mocking 1 method, while calling come real method- it means you want to do partial mocking. We call this partial mocking spying as well.
Here is a basic example:
Employee.java

/**
 *
 */
package com.sushil.mockito;

/**
 * @author Sushil
 *
 */
public class Employee {
     String name;
     int  totalMarks;
     String address;
    
     public String getName() {
              return name;
     }
     public void setName(String name) {
              this.name = name;
     }
     public int getTotalMarks() {
              System.out.println("get total marks called");
              return totalMarks;
     }
     public void setTotalMarks(int totalMarks) {
              this.totalMarks = totalMarks;
     }
     public String getAddress() {
              return address;
     }
     public void setAddress(String address) {
              this.address = address;
     }
    
     public String getSummary(String name, int marks, String address){
              System.out.println(name + " from " + address + " has recieved " + marks + " marks. " );
              return "hello I am from real class";
     }
     @Override
     public String toString() {
              return "Employee [name=" + name + ", totalMarks=" + totalMarks
                                  + ", address=" + address + "]";
     }
    
}



Test Class:
     EmployeeTest.java


/**
 *
 */
package com.sushil.mockito;

import static org.junit.Assert.fail;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * @author Sushil
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class EmployeeTest {

     @Mock
     Employee emp, spy;
    
     @Before
     public void setUp() throws Exception {
              MockitoAnnotations.initMocks(emp);
              Employee emp1=new Employee();
              emp1.setAddress("H");
              emp1.setName("K");
              emp1.setTotalMarks(20);
              spy=spy(emp1);
              int marks=spy.getTotalMarks();
       doReturn("HELLO").when(spy).getSummary(anyString(),eq(marks), anyString());
     }

     /**
      * @throws java.lang.Exception
      */
     @After
     public void tearDown() throws Exception {
     }

     @Test
     public void test() {
                  System.out.println(spy.getSummary(“Output - 1”));
                  System.out.println(spy.getSummary("L",10,"Y"));
                  System.out.println(spy.getSummary(“Output - 2”));
               System.out.println(spy.getSummary("L",20,"Y"));
     }

}


OUTPUT:


 //the real get()  method of EMPLOYEE class is called due to spy.getTotalMarks()
get total marks called


//as we have not mocked method for marks equal to 10, it calls real getSummary() method.
Output – 1  
L from Y has received 10 marks.
hello I am from real class

//as we have mocked method for marks equal to 20, it returns the result mocked.
Output - 2
HELLO

Mock it i.e. Mockito

What is Mockito ?
Now a days, we are running in sprints. Someone is having shorter sprint ( 1 week… why they call it Sprint, rename it to slow run) and someone is having longer Sprint ( 3-4 weeks, ha ha… what do you thought, will they allow you to slow walk).
Gone are the days when developer has to wait for BRD to get completed and he will get time to analyze it and then start writing code with all interaction also well defined. In the world of sprint you have to shed your weight daily and have to make sure that it will be not having impact on your health as well.
Means two things to take care
1.   Shed the weight ( produce some result daily)
2.   Make sure it is sustainable daily.
To make sure it works, we have to test it daily for its sustainability for whole sprint, but how?
We are still waiting for
1.   wheat to be grinded ( network connectivity)
2.   vegetables to be chosen ( database connectivity )
3.   Recipe to be decided ( Team members classes )
Than few wise men, will start saying ‘why not you are assuming/Predicting something, and start sprinting as whole interaction is cooperative, the person who is sprinting behind you has also assumed a lot about you.’
This saying of the wise man, can be summed up in the single sentence –
“please mock all the persons, objects or whatever you require. Predict their behavior and that is the MOCKITO”
Mockito not only allows you to mock the java class, predict its method behavior, it will even allow you to decide what it should do (in mocking world), instead of what it is doing in real world.
Mockito is the third party tool, which can be easily used to assume or predict the behavior of interacting code.
Mockito has many features let’s start with few:

Mockito Matchers

               
        Org.mockito.Matchers

Everybody do Google search daily (you reached to my blog via some search engine only), what you typed ‘mockito matchers’ in search and it rendered you my blog at 10th -12th -30th place, or might be somewhere.
What it did, it matched the string provided by you and showed you any() website which is having reference to the mockito matchers word.
This is exactly what our Mockito Matchers class do:
1.   It will allow to cutomisely mock the parameter supplied to java methods:
2.   Method paramater could be anyString(), anyInt(), anyDouble(), anyFloat(), anyObject() or eq() to something, matching to some  pattern or contains some part of given string etc..
The mockito matchers, gives you the fexibility to test your code methods, instead of a particular value, just anyXXX().
e.g.
To mock Employee class method
printSummary (name(String),total_marks(Float),Address(String)) 
and test for anyName, any marks and any aqddress print “Sushil from Bangalore got 79.5 out of 150”

we can use matchers like this:
When(mockedEmployee.printSummary(anyString(), anyFloat(), anyString())).thenReturn(“Sushil from Bangalore got 79.5 out of 150”);
Here is the list of all methods provided by matcher.
do remember all methods are static you just have to statically import org.mockito.Matcher class at the top, and then just call these methods.
1.   any() – matches anything, null as well.
2.   any(some.class) – matches the class instance of some and null as well.
3.   anyBoolean()
4.   anyChar()
5.   anyInt()
6.   anyFloat()
7.   anyByte()
8.   anyCollection(), anyCollectionof(Class<T> clazz) : matches any instance of Collection.class.
9.   anyList(), anyListof(Class<T> clazz): matches any instance of List.class
10. anyMap(), anyMapof(Class<T> clazz) : matches any instance of Map.class.
11.  anySet(),anySetOf():
12.  anyVararg() – do you want to test any number of arguments, take anyVarag() then.
Exp:
when(mockEmployee().getSummary(anyVararg())).thenReturn (“Sushil”)
it will return “sushil”, when Employee.getSummary() will called with any number of parameters.
13. contains(String substring) : check for the method parameter containing that substring.
verify(mockEmployee).getSummary(contains("Sushil"),anyint(),anyString());
14. endsWith(String suffix) : check for the method parameter ending with string.
verify(mockEmployee).getSummary(endsWith("sushil"),anyint(),anyString());
15.  eq(byte|char|float|String|int|double|T|etc…. value): it will check for the method parameter, which is equal to given value:
     verify(mockEmployee).getSummary(eq("sushil"),eq(10),anyString());
16.  isA(Class<T> clazz) : ensure the method parameter is child of clazz or clazz itself.
17.  isNotNull(), isNull()- self explainetory
18.  matches(regex) – ensure that the method parameter matching the regex value.
In our example, if we want to test only int values below 100, we can created a regex like (0-9)*10 for int value.
When((mockEmployee).getSummary(eq(“Sushil”),matches((0-9)*10)), endswith(“Bangalore”))).thenRetuern(“The worst student”)
19.   same ( T value) : object value which is same as the value passed.

20.  startsWith(String prefix) : opposite of endsWith(String suffix)

Wednesday, October 7, 2015

Binary search Brute Force


public class BinarySearchBruteForce {

static int[] elements = {1,4,6,7,9,10,15,20,56,79,90,100};


static boolean found=false;

public static void main(String[] args) {

int search=33;int index=-1;

int start=0;

int end=elements.length-1;

while(!found && start <= end){

int mid=(start+end)/2;

if(elements[mid]==search){

found=true;

index=mid;

}else if(search<elements[mid]){

end=mid-1;

}else{

start=mid+1;

}

}

if(index==-1 || !found){

System.out.println("element is not available in list");

}else{

System.out.println(""+ search+ " element is available in list at position " + 
index);

}
}

}

Binary search via recursion

public class BinarySearchRecursion {

static int[] elements = {1,4,6,7,9,10,15,20,56,79,90,100};
static int index=-1;

public static void main(String[] args) {

int index=binarySearch(elements, 0, elements.length-1, 900);

if(index==-1){

System.out.println("element is not available in list");

}else{

System.out.println("element is available in list at position "+ index);

}

}

static int binarySearch(int[] A, int start, int end, int element){

int mid=(start+end)/2;

if(end<start){

return index+1;

}

if(A[mid]==element){

index=mid;

}else if (A[mid]>element) {

binarySearch(A, start, ((start+end)/2)-1, element);

}else {

binarySearch(A, ((start+end)/2)+1,end, element);

}

return index;
}

}