Saturday, September 10, 2016

Mocking Static Methods using JMockit

What is mocking and when do we need it?
Mocking is redirecting your method call to your own defined call which will output some sample output which is defined by you. 

We use mocking mostly for Database method calls and RMI method calls, because we don't want server calls happening for unit testing our code, so instead we say to the code when you need to hit so and so methods in a class, here is what you should return, so that call will not hit the actual code but the mocked output which we provided will be returned back. 


We need the below jars for our sample tutorial:
jmockit-1.27.jar
hamcrest-core-1.3.jar and 
junit4-4.8.2.jar

Sample Code:

We can mock the static method in two ways one way is by using MockUp and other way is to use Expectations, i written code for both, but MockUp is throwing some warning so i continued using Expectations, Will explain the below logic. 

We have a static method named getDBObject(String inTable,int col) which accepts two parameters say table name and column name and say it has logic inside it which will hit the database and returns the value present in that column. As we might be using this in multiple places we don't want to hit the database for unit testing so we are mocking this method call in my UnitTesting class UtJMockTestCases. 

Let's inspect test1() method:

new Expectations(DBUtils.class) {{
DBUtils.getDBObject("one",1); result = "XYZ";
DBUtils.getDBObject("two",2); result = "ABC";
}};
assertEquals(DBUtils.getDBObject("one",1),"XYZ");
assertEquals(DBUtils.getDBObject("two",2),"ABC");
assertEquals(DBUtils.getDBObject("two",3),"Null");

these are the expectations for the BDUtils class, so we have written two expectations as of now, but if we are calling only of the method calls with the same parameters then we will get an exception saying missing one more method call, so if you need some method call to mock then only add it to expectation, rule is what ever method calls you are mocking in the expectations you should use all of them in the testingMethod here it is test1(). 

Let's inspect test2() method:
new Expectations(DBUtils.class) {{
DBUtils.getDBObject("three",anyInt); result = "ABC";
}};
assertEquals(DBUtils.getDBObject("three",1),"ABC");

so now the interesting part is the above mocking of the methods with parameters is strict checking, so when you say "one",1 it expects String to be one and integer to be 1, if you pass other say ("one",2) then you will receive Null as return because call will be gone to original method and not mocked method, so now there is a requirement like i will pass "three" as a string but i can pass any number as integer parameter so then also my mocked method should only get executed and not the original one, so in such conditions there are any* parameters in Expectations class, link, you can use it like for int it is anyInt, boolean it is anyBoolean as such and for any kind of Objects it is just any.
import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;

class DBUtils{
public static String getDBObject(String inTable,int col){
return "Null";
}
}

public class JMockTestCases {
@BeforeClass
public static void setUp(){
/*new MockUp<DBUtils>(){    
  // Redefine the method here,But With No static modifier
  @Mock
  public String getDBObject(){
   return "PERSON";
  }  
   };*/
}
@Test
public void test1() throws Exception{
new Expectations(DBUtils.class) {{
DBUtils.getDBObject("one",1); result = "XYZ";
DBUtils.getDBObject("two",2); result = "ABC";
}};
assertEquals(DBUtils.getDBObject("one",1),"XYZ");
assertEquals(DBUtils.getDBObject("two",2),"ABC");
assertEquals(DBUtils.getDBObject("two",3),"Null");
}
@Test
public void test2() throws Exception{
new Expectations(DBUtils.class) {{
DBUtils.getDBObject("three",anyInt); result = "ABC";
}};
assertEquals(DBUtils.getDBObject("three",1),"ABC");
}
}




Friday, April 8, 2016

Java Regular Expressions with small example

Problem: 
We will get the string with some format which we need to resolve into Airthemetic operations and give final result:
format for the input string:
 (operator val1 val2 (operator val3 val4 val5)  (operator val6  (operator val7 val8)))
like this
below is one example:
(+ 3 4 5) = 3+ 4+ 5 = 12
(* 2 (+ 1 3) )= 2 * (1+3) = 2*4 = 8

Solution:
I chose to solve this using Java regular expression which fits my custom needs and can solve this without relying on some third party solutions and which is also best in performance as i am using Pattern to compile and then using Matcher to find matches which will boost up the performance rather than using Pattern.matches() on the string.

Hope the below functions gives you are glance on how to solve the issue:
public static boolean hasInnerSubquery(String str){
String patternStyle = "(\\(.*(.*\\(.*\\).*).*\\)) ";
Pattern pattern = Pattern.compile(patternStyle);
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
return true;
}
return false;
}

/* this is used to resolve existing inner subqueries
* and replace the inner subquery in the string with
* the computed result and return the final replaced string
*/
public static String resolveInnerSubquery(String str) {
String patternStyle = "(\\(.*(.*\\(.*\\).*).*\\)) "; 
                //in regex grouping is done using (), and if say ([abc])([def]) that means there are
               // two groups one group which checks either a or b or c and other one group alterative
              // similarly the patternstyle i have used above checks for () inside the parenthesis --( ( ) )
             //  and try to solve the code inside the inner parenthesis.
Pattern pattern = Pattern.compile(patternStyle);
Matcher matcher = pattern.matcher(str);
int groupCount = matcher.groupCount();
while(matcher.find()){
System.out.println(matcher.group(groupCount));
String innerSubquery= matcher.group(groupCount);
innerSubquery = innerSubquery.substring(innerSubquery.indexOf('('), innerSubquery.indexOf(')')+1);
double result=calculate(innerSubquery.substring(1,innerSubquery.length()-1));
str= str.replace(innerSubquery,String.valueOf(result));
System.out.println(result);
}
return str;
}
     
     /*
* this is used to compute the final double result from the input string
* the format is like <operator> <val1> <val2> [ <val3> ...]
*/
public static double calculate(String str) {
List<String> params = null;
double result = 0;
String operator = "";
String[] strs1 = str.split("\\s+");
params = Arrays.asList(strs1);
if (params.size() >= 3) {
Iterator<String> iterator = params.iterator();
operator = iterator.next();
result = Double.parseDouble(iterator.next());
while (iterator.hasNext()) {
switch (operator) {
case "+":
result += Double.parseDouble(iterator.next());
break;
case "-":
result -= Double.parseDouble(iterator.next());
break;
case "*":
result *= Double.parseDouble(iterator.next());
break;
case "/":
result /= Double.parseDouble(iterator.next());
break;
case "%":
result %= Double.parseDouble(iterator.next());
break;
}
}
}

return result;
}

public static double performOperation(String str){
double result=0;
String input = str.substring(1,str.lastIndexOf(')'));
while(hasInnerSubquery(input)){
input=resolveInnerSubquery(input);
}
                result = calculate(input);
      }

Try this example out with your own requirements and have fun.

Monday, March 14, 2016

Creating Git Repository

Today we will try to create a Git Repository in Ubuntu Server (which is a VM) and try to access the Repository from Windows.

The steps involved are as follows:

We should be having the below prerequisites for Installing Git and (Stash/BitBucket which is Optional).

Installing Java JDK 1.8 on Ubuntu:
-----------------------------
vijay@ubuntu:~$ sudo add-apt-repository ppa:webupd8team/java
vijay@ubuntu:~$ sudo apt-get update
vijay@ubuntu:~$ sudo apt-get install oracle-java8-installer
vijay@ubuntu:~$ javac -version
javac 1.8.0_74
vijay@ubuntu:~$

Installing Perl 5.5 or above:
----------------------
vijay@ubuntu:~$ apt-get install -y perl
vijay@ubuntu:~$ perl --version
This is perl 5, version 20, subversion 2 (v5.20.2) built for x86_64-linux-gnu-thread-multi


Installing git in Ubuntu:
--------------------
vijay@ubuntu:~$ sudo apt-get install -y git
vijay@ubuntu:~$ git --version
git version 2.1.4

After Installing Git we should start working with it by acknowledging it who you are with the below two commands:

git config --global user.email "chvijay.1990@gmail.com"
git config --global user.name "vijay"

now create a folder under /opt/git/ hierarchy as below:

sudo mkdir --mode=u+rwx,g+rws,o-rwx repo1.git
sudo chown vijay.gitgroup repo1.git

This will ensure that repo1.git follow some permissions for vijay the user and gitgtoup which is our group

now run the below command inside the repo1.git directory:
git init --bare

now it will have the settings of a git repository:

Now we will try to clone it somewhere else and see whether the files got updated or not:

Create a directory in home folder as below:

sudo mkdir --mode=u+rwx,g+rws,o-rwx repos
sudo chown vijay.gitgroup repos

move to the repos directory created in your home folder and clone earlier repository

git clone vijay@192.168.183.128:/opt/git/repo1.git

Now this will create a repo1 folder in repos folder:

move to repo folder and create a file named as one.txt

append some text to it and follow the below commands:

git add one.txt
git commit -am 'fix 1'
git push origin master

After testing this inside Ubuntu VM, now you can start the work with your host OS Windows, Now before working with GIT you should install it in Windows using below link:

downloadableLink

After installing this in Windows, launch command prompt and introduce your self to Git using the earlier two commands once again:

git config --global user.email "chvijay.1990@gmail.com"
git config --global user.name "vijay"

now create a directory repos in D: directory using below commands:

D:\>mkdir repos
D:\>cd repos
D:\repos>

Now Inside this directory run the below command to get the main repository cloned to this place:

git clone vijay@192.168.183.128:/opt/git/repo1.git

After running this command the repo1 folder will be created in repos directory, in the above command 192.168.183.128 is the ipAddress of the the Ubuntu VM.

Now start working with the repository using GIT shell commands.

Have a nice time and thanks for visiting our blog :-)


Monday, March 7, 2016

Working with SubShell in Linux:

When you want to make some task got forked and get the child process run as a subshell, then you can go for the below shell script which does the same for you, increase sleep time to check the execution status of the child process with the command "ps -ef | grep sub" in one more terminal:

#!/bin/bash
while :
do
echo "[ hit CTRL+C to stop]"
echo Enter Command to Process:;
read cmd;
echo $cmd > tmp2;
(sleep 3;bash -s <tmp2 );
done


Friday, February 26, 2016

Java Reflection Work

I made small work on Java Reflection API, when ever an object is passed to the inspect() method in my code, it will try to find the attributes and their values and try to insert to DB with the same name as of the ClassName==TableName and propertiesNames==ColumnNames, this is almost similar concept to Hibernate.

I thought of resembling the same and made small assignment on my own so that it will be useful for us in future..

U can download the program from the below link:
downloadCode

I passed the object of Employee class as below:

public class Employee {

int eno;
String ename;
double sal;
int dept;
String doj;
//generate getters and setter for this
}

package org.myown;

public class Person {
int id;
String name;
String occupation;
String sex;
//generate getters and setter for this
}

You can pass any Object and see the result for yourself..!

There are few more methods which you can leverage the potential of Reflection API:

getAllFields() method will return all the fields of a class and its hiearchy superclasses till Object class.

public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
        fields.addAll(Arrays.asList(type.getDeclaredFields()));
        if (type.getSuperclass() != null) {
            fields = getAllFields(fields, type.getSuperclass());
        }
        return fields;
    }


setHierarchyPrivateField() method is used to set the private field of the current class or the private field of its super classes.

    public static void setHierarchyPrivateField(String fieldName,Object input, Object object){
        try {
            Class<?> myclass= object.getClass();
            Field field=null;
            List<Field> fields=new ArrayList<Field>();
            fields = getAllFields(fields, myclass);
            if(fields!=null) {
                Iterator<Field> itr = fields.iterator();
                while(itr.hasNext()){
                    Field fld= itr.next();
                    if(fld.toString().contains(fieldName)){
                        field = fld;
                        break;
                    }
                }
                if(field!=null) {
                    field.setAccessible(true);
                    field.set(object, input);
                    System.out.println(field.get(object).toString());
                }
            }
        } catch ( SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }


setThisPrivateField() method is used to set the private field of the current class.

    public static void setThisPrivateField(String fieldName,Object input, Object object){
        try {
            Class<?> myclass= object.getClass();
            Field field= myclass.getDeclaredField(fieldName);
                if(field!=null) {
                    field.setAccessible(true);
                    field.set(object, input);
                    System.out.println(field.get(object).toString());
                }
            } catch ( SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }


getThisPrivateField() method is used to get the private field of the current class outside of the class.

    public static Object getThisPrivateField(String fieldName,Object object){
        Object result=null;
        try {
            Class<?> myclass= object.getClass();
            Field field= myclass.getDeclaredField(fieldName);
            if(field!=null) {
                field.setAccessible(true);
                //System.out.println(field.get(object).toString());
                result=field.get(object);
            }
        } catch ( SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return result;
    }

Sunday, February 14, 2016

How to Launch Application/Server from bat file on double click? 

Hi Friends,
This is a very easy task and helpful once, u can create a shortcut for some bat files on your desktop and launch your applications straight away on double click the below is the batch program for the same, save it as a .bat file and create shortcut for it on your desktop and use it this is a very useful one and hence i thought of sharing with my friends.

setlocal
CHDIR /D D:\Tools\cis\9.1\cis-sdk\bin\
start "C:\Windows\System32\cmd.exe" launch.bat runCISAgent.py