Skip to content

To Throw or to Catch exceptions in JUnit

December 12, 2009

What would happen if an exception is thrown from the test method? Obviously the test would fail. Getting an exception is not the workflow of the code and hence the test should fail.

public void testMethod() throws checkedException{

assertEqauls(true,someMethod());

}

What if the exception is expected for a particular use case of the code. Here, getting an exception is an expected one and we don’t want the test to fail. So,we catch the exception in the try/ catch block and make the test case to win.

public void testMethod(){

try{

assertEquals(true, someOtherMethod());

fail(“Should get an Exception”);

}catch(ExpectedException e){

}

}

The above test case can be modified for the unchecked expected exception as

@Test(expected=unCheckedExpectedException.class)

public void testMethod(){

assertEquals(true,someOtherMethod());

}

Catch the exceptions only when we want the code to throw the exceptions as per the api contract. In all other cases, throw the exceptions –  all the checked exceptions ,  in the throws clause of the test method and not catch the unchecked or runtime exceptions. Let the exceptions perk up and the JUnit framework would take care of it by making the test case a failed one.

What to do when an exception occurs in the set up / tear down methods?

Getting an exception in the setUp method makes the execution to halt with failure without calling the tearDown method and thus, giving us two problems. First, if the test case constructor uses the setUp method, then we are clueless to get the underlying exception cause. Second, if a resource is initialized in the setUp method before an exception, it becomes a leaking resource as the tearDown method would never be called.

With the exception in tearDown method, the JUnit framework hides the other uncaught exceptions from the test methods and displays the exception from the tearDown method with the test error.  Hence the exceptions from the tearDown methods are to be caught and handled properly.

Advertisements

To turn off Ballon tip notifications

December 9, 2009
tags: ,

1. Run regedit.

2. Look for HKEY_CURRENT_USER \Software\Microsoft\Windows\CurrentVersion
\Explorer\Advanced.

3. Create a DWORD value (or edit it if it already exists) named EnableBalloonTips with value zero.

4. Log off and log in again.

Ref:

the productive programmer – by Neal Ford

Singletons : Is Anti-Pattern?

December 2, 2009

This was one of the long pending topic that stroked me when I was trying to create a Singleton class sometime back. What I wanted to have was a cache manager –  A CacheManager which holds all the name value pairs that were globally used by the application. So I decided to use Singleton since I would like to have global access to the NV pairs and also I would like to maintain a single instance of  the class. I made sure that  it worked with “Initialization on Demand Holder”  (lazy initialization) .

public class CacheManager {

private static final CacheManager m_instance = null;

public static CacheManager getInstance() {

if(m_instance==null)

synchronized(CacheManager.Class){

if(m_instance==null)

m_instance=new CacheManager();

}

return m_instance;

}

private CacheManager() {

//empty

}

}

Was double checking done? yes, done. Was synchronized used? yes, used.  Was ‘synchronized’  blocking the entire method and making the method costly? No, the code was blocked only when the object was created. Fine. I was happy with the CacheManager.

It worked well  for sometime and showed its bad face when multiple threads were involved.  I found that Double-checked locking was not guaranteed to work in multi threaded environment-“Double checked locking is broken-declaration”

To make it work under multiple threads, I gave up the lazy loaded feature. What if the CacheManager was initialized and was never used, the code would work  insanely. It was the pay for the thread safe implementation.

public class CacheManager{
private CacheManager() {}
private static class CacheHolder {
private static CacheManager instance = new CacheManager();
}
public static Singleton getInstance() {
return CacheHolder.instance;
}
}

Then I learned from here that, Singletons is a lie – there can be more than one instance of Singleton classes.

“When copies of the Singleton class run in multiple VMs, an instance is created for each machine.”

“When two class loaders load a class, you actually have two copies of the class, and each one can have its own Singleton instance.”

“Copies of a Singleton Object that has Undergone Serialization and Deserialization.”

Singletons cheat us from design perspective too – here, here and here.

It violates the  OO concepts of  Single Responsiblity Principle – Singleton enforces the instance policy and provides the access to configuration.

There is no way to subtype the Singleton class as the initialization cannot be overridden and there are static methods in it.

Singleton makes the unit testing harder as there is no way to mock it.

It maintains its state throughout the application and Persistent states are hard to test.

Singleton hide the dependencies and make the classes tightly coupled with each other.

Singletons are acceptable in few cases and there are some “cleaner” ways of achieving singleton benefits.  Here, Misko clearly points that Singletons are useful when there is one way flow in the application.

“Logging is perfect example. It is loaded with Singletons and global state. It is acceptable (as in it will not hurt you) because your application does not behave any different whether or not a given logger is enabled. The information here flows one way: From your application into the logger. Even thought loggers are global state since no information flows from loggers into your application, loggers are acceptable. You should still inject your logger if you want your test to assert that something is getting logged, but in general Loggers are not harmful despite being full of state.”

So,

1. Don’t use Singletons for its “GLOBAL STATE”

2. Use Singletons as STATELESS Object or as IMMUTABLE objects.

3. Use Singletons by dependency injection and make it loosely coupled with others.

Java Closure

November 26, 2009

Here is an announcement from Sun – “ Closures in JDK7 ” which is followed by so many interesting discussions on why do we need it and why we don’t. I started looking for what is closure and this post is all about what I understood by the term closure.

A closure is a first class function with free variables bounded with the lexical environment. Ok, what is a First class function? From wiki, it means constructing new functions dynamically during execution of the program, storing them in data structures, passing them as arguments to other functions and returning them as results from other functions. Though Java doesn’t support this kind of programming, it can support Functors.

Functors are one way of achieving closures  and are nothing but functions encapsulated in objects. Functor instances play the role of pointer to functions in C++ (as call back functions are used).  In Java, function objects are expressed as interface whose implementation being an anonymous inner class and there are a lot of examples for this -comparator interface, Observer interface, runnable interface.

public interface MyComparator implements Comparable{

public int compare(int i1, int i2);
}

MyComparator  comparator1=new MyComparator(){
public int compare(int s1, int s2){
//compare s1 and s2 here
return 1;
}
};
//Use comparator1 to sort elements in the list
MyList.sort(new ArrayList(12,56),comparator1);

Here, MyCompartor is a class which implements the Comparable interface. The instance of MyComparator is a function object whose function is to say, compare two integers. The function object comparator1 is passed to the method sort to

Using the concept of Generics,

public interface MyComparator<I,O>{

public O compare(I i1, I i2);
}

MyComparator<String, Boolean> comparator2=new MyComparator<String, Boolean>(){
public Boolean compare(String s1, String s2){
//compare s1 and s2 here
return true;
}
};
//Use comparator1 to sort elements in the list
MyList.sort(new ArrayList(“hai”,”hi”),comparator2);

MyList.sort(new ArrayList(57,89,23,54),comparator1);

Functors also help in achieving code reusability by composition as in Decorator pattern,strategy pattern,command pattern and visitor pattern.

public enum Season{
SUMMER{ protected void display() {
System.out.println(“mar to may”);
}},

WINTER{ protected void display() {
System.out.println(“nov to feb”);
}},

SPRING{ protected void display() {
System.out.println(“jun to oct”);
}};

protected abstract void display();

public void duration() {
display();
}
}

Closures are often mistaken for the anonymous functions. Some programming languages, use anonymous functions to have the closures. But, the two are different. An anonymous function doesn’t capture the lexical environment where as the closure does. Hence, using closures can extend the lifetime of objects which may hinder the performance.

Here are some proposals for the syntax for Closures – http://jroller.com/scolebourne/ .

Writing tests loosely coupled with environment :

November 20, 2009
tags: ,

For better testing, follow – “Simulate things rather than recreating it”.

Suppose we want to test the condition for non existence for file, usally we will pass some invalid filenames and try to catch the exception. This is a  good short cut and it works fine.

class ReadFileTestCase extends TestCase{

public void testFileDoesNotExist(){
try{
Encoder encoder=new Encoder(reader);
encoder.encode(new File(“c:\invalidFile”));
}catch(FileNotFoundException fef){

}
}
}

The problem is,we are recreating the situation and not simulating it. Here, it works well in your environment. When the code is moved to another machine which contains a file named as invalidFile, then the test fails. It may lead to confusions as the test fails not because of code but of more dependency on the environment.

To avoid that, create a mock which will throw the invalid file name exceptions for whatever objects you pass.

class ReadFileTestCase extends TestCase{

public void testFileDoesNotExist(){
ReaderMock mock =new ReaderMock();
mock.setInvalidFiles();
try{
Encoder encoder=new Encoder(mock);
encoder.encode(new File(“c:\myFile”));
}catch(FileNotFoundException fef){

}
}
}

Thats it. The test will pass for all inputs and on all environments.

To avoid windows restarting after automatic updates

November 13, 2009
tags: ,

just run the below  in command prompt

> net stop wuauserv
Click here for what is wuauserv ?

Eclipse : JVM terminated exit code=1

November 11, 2009
tags:

eclipseerror

I got the JVM terminated error while starting the eclipse with some added plugins.

On googling, I found some of the causes for the termination.

1.check if jre version >= 5
2. lock issues in case eclipse didnt shut down properly
3. check the eclipse.ini file for duplicate entries
4. check eclipse.ini for the available heap size for JVM.
-vmargs
-Xms40m
-Xmx256m

I tried all the above and upon decreasing the heap size, the eclipse started.