Unit Test: JUnit 4 and Mockito

Hi,

This post is about unit testing. Writing tests, as you already know, is very important. The more important thing, as I learnt lately, is writing testable code. Writing testable code requires more intelligent designs and hard work. Also you must expect your workers or colleagues or boss might be get upset when you try to write or make them to write testable code, because it will take time. But think that way; you write your business logic in 3 days and writing tests on them takes 10 days. Not this only, you change your business logic whenever you get stuck on writing test, and worst you drop writing test at all. Am I exaggerating? No, I don’t think so. You must spend your time on your business logic, it will be responsible for work not tests. So, maybe you are asking yourselves that why I’m writing tests. In fact if you are here, then you know the importance of it. You can (and should) read from Miško Hevery‘s blog. He is fantastic and he has valuable thoughts on testing. I’m stopping talking about philosophy of testing and coming to action, read Miško Hevery, seriously.

The code I will share is about testing your code using JUnit and Mockito. I’ll not talk about JUnit, I’ll talk about Mockito a bit and show them to you in action in a dummy project.

You wrote your code, you are sure it will work. Your classes are full of intelligent decisions and designs. But at some point they are all dependent of others. Others depends on others etc. The meaning of unit test is testing units of your project in isolation. Class A depends on B and C but in TestA.java you should concentrate on only A. So you must find a way to simulate B and C in a way that they work perfectly. Mockito comes here to solve your problems. (Misko Hevery has some posts on dependencies in classes, they might help you at this point.) Create mocks(simulations) of your dependencies, provide them some functionality and let them go. You must test your units one by one in unit tests. You can read about Mockito here, and JUnit here.

Here is the class:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class DummyFileReader {
 public void readNames(String path) {
 InputStream resourceAsStream = DummyFileReader.class.getResourceAsStream(path);
 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream));
 String name;
 try {
 while ((name = bufferedReader.readLine()) != null) {
 System.out.println(name);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
}

And here is the test class:

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doThrow;
public class DummyFileReaderTest {
 @Mock
 DummyFileReader dummyFileReader;
@Rule
 public ExpectedException expectedException = ExpectedException.none();
@Before
 public void setup() {
 MockitoAnnotations.initMocks(this);
 doThrow(new RuntimeException("Intended Exception")).when(dummyFileReader).readNames(anyString());
 }
@Test
 public void testReadNames() throws Exception {
 expectedException.expect(RuntimeException.class);
 expectedException.expectMessage("Intended Exception");
dummyFileReader.readNames("names");
 }
}

I have a class that has only one method “readNames” which has no return value. Mockito has a problem about void methods. If you don’t mock the method then they do nothing. If you mock them you have 2 options, doNothing and doThrow. I want to show you that you can use ExpectedException annotation to test your void methods with cooperation of Mockito and JUnit. Now you can test your mocks which have doThrow functionality using ExpectedException. You could use @Test(expected = MyException.class) but you have more control(eg. message of exception) over your tests now.

One point; Mockito.doThrow can only throw unchecked exceptions.

You can find the source code here.

Creating SSL Keystore For Apache Tomcat Using Keytool and BouncyCastle

This post is explaining how to create your own ssl keystore file and using it in your Android applications. I have taken the example from http://stackoverflow.com/questions/4065379/how-to-create-a-bks-bouncycastle-format-java-keystore-that-contains-a-client-c.

Download bouncycastle JAR from http://repo2.maven.org/maven2/org/bouncycastle/bcprov-ext-jdk15on/1.47/bcprov-ext-jdk15on-1.47.jar
Configure BouncyCastle for PC using one of the below methods.
Adding the BC Provider Statically (Recommended)

Copy the bcprov-ext-jdk15on-1.47.jar to each
jdk1.6.0_33\jre\lib\ext (JDK bundled JRE)
jre1.6.0_33\lib\ext (JRE)
C:\ (location to be used in env variable)
Modify the java.security file under
jdk1.6.0_33\jre\lib\security
jre1.6.0_33\lib\security
and add the following entry
security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider
Edit your path and add this entry:

c:\bcprov-ext-jdk15on-1.47.jar
Generate the Keystore using Bouncy Castle
Run the following command
keytool -genkey -alias changeit -keystore C:/changeit.keystore -storepass changeit -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider

Note: You should write your ip when it asks: What is your first and last name?
This generates the file C:\changeit.keystore

Run the following command to check if it is properly generated or not
keytool -list -keystore C:\changeit.keystore -storetype BKS

Configure BouncyCastle for TOMCAT

Open apache-tomcat-6.0.35\conf\server.xml and add the following entry
<Connector port=”8443″ keystorePass=”changeit” alias=”changeit” keystore=”c:/changeit.keystore” keystoreType=”BKS” SSLEnabled=”true” clientAuth=”false” protocol=”HTTP/1.1″ scheme=”https” secure=”true” sslProtocol=”TLS” sslImplementationName=”org.bouncycastle.jce.provider.BouncyCastleProvider”/>

Restart the server after these changes.

Go to https://localhost:8443/, you should see Tomcat homepage.

You should check Stackoverflow link above to get whole example. I should say that Vipul has made a great work.

Flex – Java Real Time Chart With BlazeDS

In my previous post I’ve explained how to create a line chart populated with real time data.

In this post I’ve moved real time data generating to Java project and push that data to client using BlazeDS. The rest is same as the previous flex project.

I’ll simply put sources here so you can take a look at it. You need to modify build.xml in java project according to your system. Also right click on your flex project in your Flash Builder  and select properties. Flex Compiler->Additional Compiler Arguments then modify path. You will be able to deploy the java project war file to tomcat and run your flex project from Flash Builder.

You will see the live data in line chart generated and pushed from the server.

There are 2 projects(RealTimeDataServer, RealTimeLineChart) one for server-side with BlazeDS and the other for client with Flex:

GitHub

Creating android library project with eclipse

I’ve two versions of my project. One for phones and one for tablet pc. The problem is they share a lot of functionality. The one for phones is using tabhost and the other one not using it but services, activities and permissions are the same more or less.

So I decided to sum these  common points in a library project so I get rid of duplication of work.

First thing is creating a new  android application in eclipse. Name it TestLibProject. Make it Library Project by Right Click on this project and Properties->Android then check the Is Library option. You can find this information from http://developer.android.com/guide/developing/projects/projects-eclipse.html

Anyway as the link says create another project that will be using this library project. Name it TestClientProject. Right click this project and  Properties->Android then in library panel click ‘Add’. You will see your lib project named  TestLibProject. Select and add it.

You will notice that under your   TestClientProject->Library Projects you have  testlibproject.jar exists. That jar contains the classes of your lib project.

Let’s create a dummy service that prints the time to console. It’s really dummy sorry 🙂

The Library Project( TestLibProject  ) :

DummyService.java

public class DummyService extends Service
{

 @Override
 public void onCreate()
 {
 super.onCreate();
 DummyThread dummyThread = new DummyThread();
 dummyThread.start();
 }

 @Override
 public IBinder onBind(Intent arg0)
 {
 return null;
 }

 private class DummyThread extends Thread
 {
 public DummyThread()
 {
 this.setName("DummyThread");
 }

 @Override
 public void run()
 {
 while (true)
 {
 Log.e(getName(), new Date().toLocaleString());
 try
 {
 sleep(1000);
 }
 catch (InterruptedException e)
 {
 e.printStackTrace();
 }
 }
 }
 }
}

AndroidManifest.xml

It is really interesting here. You don’t need to declare anything here. But you will need to declare your services, activities or anything you will use in your client project. But it is advised to declare these in here too.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.lib.package" >

    <service android:name=".DummyService" >
    </service>

</manifest>

The Client Project( TestClientProject ) :

TestClientProjectActivity.java:

BEWARE: You may need to restart eclipse to make your client project to recognize DummyService class.

public class  TestClientProjectActivity extends Activity
{
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 Intent intent = new Intent(this,  DummyService.class);
 startService(intent);
 }
}

AndroidManifest.xml:
As I said before we need to declare our service here.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="your.client.package"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk android:minSdkVersion="8" />

 <application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name" >
 <activity
 android:name=".TestClientProjectActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <service android:name="your.lib.package.DummyService" >
 </service>
 </application>

</manifest>

When you run your client project you will see logs like that:

01-27 03:20:43.855 E/DummyThread ( 281): Jan 27, 2012 3:20:43 AM
01-27 03:20:44.913 E/ DummyThread ( 281): Jan 27, 2012 3:20:44 AM
01-27 03:20:45.973 E/ DummyThread ( 281): Jan 27, 2012 3:20:45 AM
01-27 03:20:46.984 E/ DummyThread ( 281): Jan 27, 2012 3:20:46 AM
01-27 03:20:47.993 E/ DummyThread ( 281): Jan 27, 2012 3:20:47 AM
01-27 03:20:49.013 E/ DummyThread ( 281): Jan 27, 2012 3:20:49 AM
01-27 03:20:50.072 E/ DummyThread ( 281): Jan 27, 2012 3:20:50 AM
01-27 03:20:51.093 E/ DummyThread ( 281): Jan 27, 2012 3:20:51 AM
01-27 03:20:52.103 E/ DummyThread ( 281): Jan 27, 2012 3:20:52 AM
01-27 03:20:53.108 E/ DummyThread ( 281): Jan 27, 2012 3:20:53 AM

Our library project works!

Happy coding…

No generator named “X” is defined in the persistence unit – Eclipse JPA

Hi,

If you are working with a JPA project using Eclipse sometimes you need generators. But Eclipse JPA plug-in (Dali) complains about custom generators:

 

@GeneratedValue(generator = “foreign“)
@GenericGenerator(name = “foreign“, strategy = “foreign”, parameters = { @Parameter(name = “property”, value = “yourEntity”) })

 No generator named “foreign” is defined in the persistence unit

 

The solution, I don’t like it though, is  Window->Preferences->Java Persistence->JPA->Errors/Warnings->Queries and Generators and set level of “Generator is not defined in the persistence unit” to warning. You are ok now.

Java Serial Programming – Checking Ports

I’m developing an application on android and I need to read from my tablet’s usb port. I’m using a rs232 to usb  chip because  my other device sends data from its serial port and my tablet has no serial port. As you already know whenever you unplug your usb/serial device from your computer and then plug it again, usually its port number changes. For example before unplugging your device the port number was ttyUSB1 but re-plugging it makes the number ttyUSB7 or whatever. I couldn’t find anyway to stop that. If you know a solution for this, please inform me.

You can list plugged devices’ port using Java. I’ll provide sample code for this:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.Vector;

public class PortFinder
{
 public class Driver
 {
 public Driver(String name, String root)
 {
 mDriverName = name;
 mDeviceRoot = root;
 }

 private String mDriverName;
 private String mDeviceRoot;
 Vector<File> mDevices = null;

 public Vector<File> getDevices()
 {
 if (mDevices == null)
 {
 mDevices = new Vector<File>();
 File dev = new File("/dev");
 File[] files = dev.listFiles();
 int i;
 for (i = 0; i < files.length; i++)
 {
 if (files[i].getAbsolutePath().startsWith(mDeviceRoot))
 {
 System.out.println("Found new device: " + files[i]);
 mDevices.add(files[i]);
 }
 }
 }
 return mDevices;
 }

 public String getName()
 {
 return mDriverName;
 }
 }

 private Vector<Driver> mDrivers = null;

 Vector<Driver> getDrivers() throws IOException
 {
 if (mDrivers == null)
 {
 mDrivers = new Vector<Driver>();
 LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
 String l;
 while ((l = r.readLine()) != null)
 {
 // Issue 3:
 // Since driver name may contain spaces, we do not extract
 // driver name with split()
 String drivername = l.substring(0, 0x15).trim();
 String[] w = l.split(" +");
 if ((w.length >= 5) && (w[w.length - 1].equals("serial")))
 {
 System.out.println("Found new driver " + drivername + " on " + w[w.length - 4]);
 mDrivers.add(new Driver(drivername, w[w.length - 4]));
 }
 }
 r.close();
 }
 return mDrivers;
 }

 public String[] getAllDevices()
 {
 Vector<String> devices = new Vector<String>();
 // Parse each driver
 Iterator<Driver> itdriv;
 try
 {
 itdriv = getDrivers().iterator();
 while (itdriv.hasNext())
 {
 Driver driver = itdriv.next();
 Iterator<File> itdev = driver.getDevices().iterator();
 while (itdev.hasNext())
 {
 String device = itdev.next().getName();
 String value = String.format("%s (%s)", device, driver.getName());
 devices.add(value);
 }
 }
 }
 catch (IOException e)
 {
 e.printStackTrace();
 }
 return devices.toArray(new String[devices.size()]);
 }

 public String[] getAllDevicesPath()
 {
 Vector<String> devices = new Vector<String>();
 // Parse each driver
 Iterator<Driver> itdriv;
 try
 {
 itdriv = getDrivers().iterator();
 while (itdriv.hasNext())
 {
 Driver driver = itdriv.next();
 Iterator<File> itdev = driver.getDevices().iterator();
 while (itdev.hasNext())
 {
 String device = itdev.next().getAbsolutePath();
 devices.add(device);
 }
 }
 }
 catch (IOException e)
 {
 e.printStackTrace();
 }
 return devices.toArray(new String[devices.size()]);
 }

 public static void main(String args[])
 {
 PortFinder portFinder = new PortFinder();
 String[] devices = portFinder.getAllDevices();
 String[] devicePaths = portFinder.getAllDevicesPath();
 for (int i = 0; i < devices.length; i++)
 {
 System.out.println("Device:->" + devices[i] + " Path:->" + devicePaths[i]);
 }
 }
}
 

Using this you will be able to operate (change permission, close, open, write, read etc) on your correct port without looking at /dev.

And the output is(Pay attention to Device:->ttyUSB0 (usbserial) Path:->/dev/ttyUSB0)

Found new driver usbserial on /dev/ttyUSB
Found new driver rfcomm on /dev/rfcomm
Found new driver serial on /dev/ttyS
Found new device: /dev/ttyUSB0
Found new device: /dev/ttyS31
Found new device: /dev/ttyS30
Found new device: /dev/ttyS29
Found new device: /dev/ttyS28
Found new device: /dev/ttyS27
Found new device: /dev/ttyS26
Found new device: /dev/ttyS25
Found new device: /dev/ttyS24
Found new device: /dev/ttyS23
Found new device: /dev/ttyS22
Found new device: /dev/ttyS21
Found new device: /dev/ttyS20
Found new device: /dev/ttyS19
Found new device: /dev/ttyS18
Found new device: /dev/ttyS17
Found new device: /dev/ttyS16
Found new device: /dev/ttyS15
Found new device: /dev/ttyS14
Found new device: /dev/ttyS13
Found new device: /dev/ttyS12
Found new device: /dev/ttyS11
Found new device: /dev/ttyS10
Found new device: /dev/ttyS9
Found new device: /dev/ttyS8
Found new device: /dev/ttyS7
Found new device: /dev/ttyS6
Found new device: /dev/ttyS5
Found new device: /dev/ttyS4
Found new device: /dev/ttyS3
Found new device: /dev/ttyS2
Found new device: /dev/ttyS1
Found new device: /dev/ttyS0
Device:->ttyUSB0 (usbserial) Path:->/dev/ttyUSB0
Device:->ttyS31 (serial) Path:->/dev/ttyS31
Device:->ttyS30 (serial) Path:->/dev/ttyS30
Device:->ttyS29 (serial) Path:->/dev/ttyS29
Device:->ttyS28 (serial) Path:->/dev/ttyS28
Device:->ttyS27 (serial) Path:->/dev/ttyS27
Device:->ttyS26 (serial) Path:->/dev/ttyS26
Device:->ttyS25 (serial) Path:->/dev/ttyS25
Device:->ttyS24 (serial) Path:->/dev/ttyS24
Device:->ttyS23 (serial) Path:->/dev/ttyS23
Device:->ttyS22 (serial) Path:->/dev/ttyS22
Device:->ttyS21 (serial) Path:->/dev/ttyS21
Device:->ttyS20 (serial) Path:->/dev/ttyS20
Device:->ttyS19 (serial) Path:->/dev/ttyS19
Device:->ttyS18 (serial) Path:->/dev/ttyS18
Device:->ttyS17 (serial) Path:->/dev/ttyS17
Device:->ttyS16 (serial) Path:->/dev/ttyS16
Device:->ttyS15 (serial) Path:->/dev/ttyS15
Device:->ttyS14 (serial) Path:->/dev/ttyS14
Device:->ttyS13 (serial) Path:->/dev/ttyS13
Device:->ttyS12 (serial) Path:->/dev/ttyS12
Device:->ttyS11 (serial) Path:->/dev/ttyS11
Device:->ttyS10 (serial) Path:->/dev/ttyS10
Device:->ttyS9 (serial) Path:->/dev/ttyS9
Device:->ttyS8 (serial) Path:->/dev/ttyS8
Device:->ttyS7 (serial) Path:->/dev/ttyS7
Device:->ttyS6 (serial) Path:->/dev/ttyS6
Device:->ttyS5 (serial) Path:->/dev/ttyS5
Device:->ttyS4 (serial) Path:->/dev/ttyS4
Device:->ttyS3 (serial) Path:->/dev/ttyS3
Device:->ttyS2 (serial) Path:->/dev/ttyS2
Device:->ttyS1 (serial) Path:->/dev/ttyS1
Device:->ttyS0 (serial) Path:->/dev/ttyS0

Running Shell Commands With Java As Root

For a long time I’ve been searching for running sudo commands without password prompt in Java. I’ve seen a post by Saeid Zebardast and thanks to him I solved that issue.

First you need  to edit /etc/sudoers file:

$ sudo gedit /etc/sudoers

and add that lines to this file:

# for user
YOUR_USER_NAME ALL= NOPASSWD: ALL

# for group
YOUR_GROUP_NAME ALL= NOPASSWD: ALL

Although the first line is worked for me, Saeid suggests adding both.

Anyway, after that change you can run your sudo command within Java:

String command = "sudo chmod 777 /home/gokceng/Desktop/test.my";
 Runtime runtime = Runtime.getRuntime();
 try
 {
 Process process = runtime.exec(command);
 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
 String line;
 while ((line = bufferedReader.readLine()) != null)
 {
 System.out.println(line);
 }
 }
 catch (IOException e)
 {
 e.printStackTrace();
 }