Maven Global dependency exclusion

With Maven becoming the build tool of choice for Jave EE developers, one of the problems that a developer faces frequently is that of Transitive dependencies. Problems like ClassCastException and LinkageError  are encountered during deployment of an application because of the same class being loaded by different ClassLoaders  or presence of different versions of the same set of APIs as a result of transitive dependency.

Such issues become even more elusive to debug if the Application server your using comes bundled with a whole galaxy of commonly used jar files(yes i am talking ’bout JBoss :D).  Lets see couple of such cases.

Read more of this post

Spring Singleton, Request, Session Beans and Thread Safety

The Spring framework ecosystem comprising of so many useful frameworks has become the backbone of many Java EE application. But at the core of all the spring products we still have the Spring DI/IOC framework which has catapulted Spring to all new heights. As more people are adopting Spring MVC or a JSF-Spring integration for their application, the Spring beans are now more frequently used with request/session scope apart from their more traditional counterparts of Singleton and  Prototype scopes.

One of the initial curiosities of a developer just starting out with various Spring scopes is that how do these scope behave in a web application and in situations which require writing safe concurrency code. Well the answer to this no to over-think about these scope as they behave exactly the way they have been named.  Let’s take a example of JSF- Spring integration wherein all the JSF beans are loaded by the Spring IOC container and Scope of the beans are also defined using suppose Spring’s @Scope annotation. Read more of this post

Using PowerMock to mock/stub static void method calls in JUnit.

Sometimes  you do come across snippets of code that prove to be tricky while writing their JUnit tests.  One such scenario is the case of static void call, though some people would argue to extract the static void call into a separate method but that is old-school. PowerMock junit runner lets you  even mock static void and normal static calls. Let us take a look at both approaches the old one and the new one which uses PowerMock.

Older Approach


public class MyAction {

public String performSearch() {

// some logic operations

// the detestable static call
staticCall();

return "Success";
}

protected void staticCall() {
// <strong>the static void method call</strong>
MyStatic.staticMethod();
}

}

class MyStatic {

public static void staticMethod() {
throw new NullPointerException("Bazinga!");

}

}

In the above code snippet we can see that the static void call is extracted out in a separated method, now while writing the JUnit test for MyAction java class we can have anonymous sub-class which overrides the staticCall() method with it’s own implementation to avoid calling this method. Below code snippet elucidates the overriding

public class MyActionTest {

MyAction action;

@Before
public void setUp() {
action = new MyAction(){
protected void staticCall() {

System.out.println("inside overridden method");
};
};
}

In the above snippet we can see that I have overridden the staticCall() method, now while executing the Junit test the super-class method containing the static call is never invoked and hence our purpose is solved of avoiding the static call. But the reason I don’t consider this approach clean is that our code should not be changed in order to  make our Junit tests easier to write. Junit test should test existing running code without the need of modifying the code to meet JUnit’s need.

Now lets use PowerMock to mock the static void calls.


@RunWith(PowerMockRunner.class)
@PrepareForTest(MyStatic.class)
public class MyActionTest {
MyAction action;

@Before
public void setUp() {
action = new MyAction();
}

@Test
public void testPerformSearch() {

PowerMockito.spy(MyStatic.class);
PowerMockito.doNothing().when(MyStatic.class);
MyStatic.staticMethod();
Assert.assertEquals("Success", action.performSearch());
}
}

In the above code we have used PowerMock’s spy feature to partially mock the object, once you partial mock the object you have to stub the behavior i.e. prepare some canned calls. Here the PowerMock’s ability lies in the below three statements

PowerMockito.spy(MyStatic.class);
PowerMockito.doNothing().when(MyStatic.class);
MyStatic.staticMethod();

First we partially mock the MyStatic Class, then in the second line the doNothing() method is used to specify that the A static method call by the class MyStatic should result in doing nothing. Now since the object is partially mocked thus we also need to specify the method whose invocation is canned by doNothing() method, we do this in the 3rd statement MyStatic.staticMethod() , thus now it’s more of record-playback pattern wherein we have initially recorded the doNothing() behavior and then played the MyStatic.staticMethod().

Conclusion   The PowerMock approach is best possible solution i could find for mocking static calls without changing actual code, if you have any other tricks up your sleeve do share them!

You can download the powermock mocktio jars zip from here

JUnit Spring session and request scope beans.

While writing units test using SpringJUnit4ClassRunner, the issue that comes up very often is what to do for beans that are request and session scope. These beans are generally injected as dependency using Autowired annotation within another bean. Lets see the example

 @Component
 @Scope("session")
 class Order{
 }

The above Order bean is session scope and suppose it’s injected within Person bean below

@Component
public class Person {
@Autowired
Order order;
}

Now in the above code, you are bound to get
java.lang.IllegalStateException: No Scope registered for scope ‘session’

Though there are multiple solutions for this available on the Internet, some suggest mocking while other suggest to use single scoped Order bean in the test configuration file(bad practice!).

The thing which worked for me was the below XML snippet in my Test configuration file


<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="session">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>

Since Junits are executed in a single thread thus a simple thread-bound session scope is available which maintains it’s states between the tests.

Share

QuickTip: maven jetty plugin issue

The following issue is encountered most of the times in maven war projects when you type “mvn clean jetty:run” in the command line and hope to see your WAR project deployed on jetty but instead you get the dreaded error.

[ERROR] BUILD ERROR
[INFO] ————————————————————————
[INFO] The plugin ‘org.apache.maven.plugins:maven-jetty-plugin’ does not exist or no valid version could be found
[INFO] ————————————————————————
[INFO] For more information, run Maven with the -e switch

The easiest way to fix this issue is to give complete info about the jetty plugin in the command line and deploy your WAR file i.e.
mvn org.mortbay.jetty:maven-jetty-plugin:run

The above command should fix your problem.

Share