Mockito and Power Mockito – Cheatsheet

@RunWith(PowerMockRunner.class) – Tell Junit that run this test using PowerMockRunner

@PrepareForTest(A.class) – This is needed when we need to test static methods of A class

AService mock = PowerMockito.mock(A.class) – Creating a mock for A class

PowerMockito.when(mock.mockedMethod()).thenReturn(value) – When mockedMethod is called in the code, then return the value specified here.

PowerMockito.doNothing().when(mock).method() – do nothing when method() is called on mock object

Mockito.verify(mock).someMethod() – Verify that someMethod was called on mock once.

Mockito.verify(mock, times(n)).someMethod() – someMethod called n number of times

Mockito.verify(mock, never()).someMethod() – someMethod called n number of times

Mockito.verify(mock, atLeastOnce()).someMethod() – self explanatory

Mockito.verify(mock, atLeast(n)).someMethod() – self explanatory

Mockito.verify(mock, atMost(n)).someMethod() – self explanatory

Static

PowerMockito.mockStatic(A.class) – mock all static methods of class A

PowerMockito.doNothing().when(A.class)
A.staticMethod(value); – Nothing to be done when staticMethod(value) is called on class A

PowerMockito.doNothing().doThrow(new IllegalStateException()).when(A.class)
A.staticMethod(value); – Throw IllegalStateException when staticMethod(value) is called on class A

//We first have to inform PowerMock that we will now verify
//the invocation of a static method by calling verifyStatic.
PowerMockito.verifyStatic();
//Then we need to inform PowerMock about the method we want to verify.
//This is done by actually invoking the static
A.staticMethod();

@Before – annotation for a method that does the set up before starting the test.

InOrder verification

//First we have to let PowerMock know that the verification order is
//going to be important. This is done by calling Mockito.inOrder and passing
//it the mocked object.
InOrder inOrder = Mockito.inOrder(mock);
//Next, we can continue our verification using the inOrder instance
//using the same technique as seen earlier.
inOrder.verify(mock).isNew();
inOrder.verify(mock).update();
inOrder.verify(mock, Mockito.never()).create();

Constructor

PowerMockito.whenNew(A.class).withArguments(mock, “msg”).thenReturn(object)

PowerMockito.verifyNew(A.class).withArguments(mock, “msg”)
PowerMockito.verifyNew(A.class, times(n)).withArguments(mock, “msg”)

The class creating an object of A will be needed to be in @PrepareForTest

Matchers

PowerMockito.when(mock.method(Mockito.startsWith(“somestring”))).thenReturn(objValue);
Assert.assertSame(objValue, mock.method(“somestring123”));
Assert.assertSame(objValue, mock.method(“somestring456”));

PowerMockito.when(mock.method(Mockito.argThat(new ArgumentMatcher){public void matches(Object obj)….}).thenReturn(value); – Use the custom matcher to match the argument and return the value specified.

Mockito.eq(value)
Mockito.matches(regex)
Mockito.anyString, anyFloat, anyDouble, anyList, and so on
Mockito.isNull
Mockito.isNotNull
Mockito.isA
Mockito.endsWith

Answer Interface

When thenReturn() is not practical, use Answer interface

PowerMockito.when(mock.method()).then(new Answer<T>() {
public T answer(InvocationOnMock invocation) {
…invocation.getArguments()….
}
});

PowerMockito.mock(A.class, Answer obj) – This will act as default answer for all the invocation on this mock object.

Spy – Partial Mocking (some methods) of classes

//Following is the syntax to create a spy using the PowerMockito.spy method.
//Notice that we have to pass an actual instance of the EmployeeService class.
//This is necessary since a spy will only mock few methods of a class and
//invoke the real methods for all methods that are not mocked.
final EmployeeService spy = PowerMockito.spy(new EmployeeService());

//Notice that we have to use the PowerMockito.doNothing().when(spy).createEmployee()
//syntax to create the spy. This is required because if we use the
//PowerMockito.when(spy.createEmployee()) syntax will result in calling
//the actual method on the spy.
//Hence, remember when we are using spies,
//always use the doNothing(), doReturn() or the //doThrow() syntax only. PowerMockito.doNothing().when(spy)
.createEmployee(employeeMock);

Mocking private methods

PowerMockito.doNothing().when(spy,
“createEmployee”, employeeMock);

PowerMockito.verifyPrivate(spy)
.invoke(“createEmployee”, employeeMock);

Advertisements

Spring Core Reference – Cheatsheet

Factory
=======

BeanFactory factory  = new XmlBeanFactory(new FileSystemResource(fileName));
factory.getBean(beanName);

ApplicationContext context = new ClassPathXmlApplicationContext(fileName);
context.getBean(beanName);

Property
========

By Value
<bean id=”beanName” class=”org.abcd.efg.AClass”>
<property name=”name” value=”Rasesh”/>
</bean>

By Reference
<bean id=”beanName” class=”org.abcd.efg.AClass”>
<property name=”name” ref=”anotherBeanName”/>
</bean>

Constructor
==========

<bean id=”beanName” class=”org.abcd.efg.AClass”>
<constructor-arg index=”0″ value=”Rasesh”/>
<constructor-arg index=”1″ ref=”anotherBeanName”/>
</bean>

Collections
=========

<bean id=”beanName” class=”org.abcd.efg.AClass”>
<property name=”names” >
<list>
<ref bean=”beanName”/>
<ref bean=”anotherBeanName”/>
</list>
</property>
</bean>

Autowiring by tags
===============

ByName
<bean id=”beanName” class=”org.abcd.efg.AClass” autowire=”byName“>
</bean>

Here, it will search for the beans with the same name as member variables in AClass and autowire them.

ByType
<bean id=”beanName” class=”org.abcd.efg.AClass” autowire=”byType“>
</bean>

Here, it will try and match the data type of beans and member variables in AClass. If there are multiple beans of same data type, this won’t work.

Constructor
<bean id=”beanName” class=”org.abcd.efg.AClass” autowire=”constructor“>
</bean>

This is autowire by Type, but this will set the member variables through constructor instead of setters.

Bean Scopes
===========

Singleton, Prototype

Annotations
==========

@Required
Adding Required annotation to setter will fail when it initializes the bean if the value is null instead of a later NPE when it is referenced.

<bean class=”org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor” />

This bean will take care of the process mentioned above.

@Autowired
This works same as auto-wiring by type falling back to auto-wiring by name. If still not found, qualifier can be used.

<bean id=”……>
<qualifier value=”qualifierString”/>

</bean>

<context:annotation-config/> can be used to avoid adding bean post processor for each annotation.

This along with @Qualifier(“qualifierString”) will be able to auto wire the bean.
<bean class=”org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor” />

@Resource
This can be used for dependency injection by name. @Resource(name=”beanName”) will wire the bean with specified name.

If name is not specified, it will do auto-wiring by name.

@PostConstruct and @PreDestroy can be used for init method and destroy method with context.registerShutDownHook().

@Component

This can be used to avoid xml configuration and spring will create a bean named as the class’s name. This can only handle singleton bean.

<context:component-scan base-package=”org.abcd.efg”/>

@Service, @Controller, @Repository

component-scan tag will pick this up as well. These map to MVC data model.

MessageSource to get text from property files
=====================================

<bean id=”messageSource” class=”org.springframework.context.support.ResourceBundleMessageSource”>
<property name=”basenames”>
<list>
<value>mymessages</value>
</list>
</property>
</bean>

context.getMessage(“greeting”, null, //message parameter
“Default greeting”, null //Locale
);

OR

MessageSource messageSource = context.getBean(“messageSource”);
messageSource.getMessage(“greeting”, null, //message parameter
“Default greeting”, null //Locale
);

parameter ex:

drawing.point=Circle: Point is: ({0}, {1})
context.getMessage(“drawing.point”, new Object[] {“val1”, “val2”}, “Default point msg”, null)

JDK Tools for your application

In this post, I will talk about various tools that help you analyze your Java application’s behavior when something has went wrong. This is not an exhaustive list but just the tools that I have used at some point of time and found useful.

1. jmap
This is a tool bundled within JDK and useful for connecting to either running java processes locally/remotely or connecting to a core file.

  • Heap Dump: jmap -dump:format=b,file=/tmp/heap.bin PID
    This command dumps the heap which can be later analyzed using other tools mentioned below to analyze the application’s memory usage.
  • Heap Summary: jmap -heap PID
    This command dumps the current memory usage with the division of heap space (Young Gen/Old Gen/Survivor Space) depending on the Garbage Collector used

2. jstack
This tool is also included in JDK and useful to get details of a running application.

  • Thread details: jstack -l PID
    This command will print the stack trace of all the threads running in the java process. This can be used to get total threads with priority details of those threads.

3. jhat
Bundled within JDK, this tool can be used to analyze the heap dump

  • Heap Dump Analysis: jhat Heap_Dump_File
    This command will analyze the heap dump file extracting all the object details and publish this details to a web server running on default 7000 port (can be changed using options) where you can see all the object details and even run Object Queries (OQL) against the heap dump.

4. jvisualvm
This tool is also available within JDK and provides UI to connect to running java process and can be used to get a heap dump or used as a profiler.

5. MAT
Memory Analyzer Tool is an eclipse plugin used for heap dump analysis and very useful to find memory leaks or checking the heap usage of the application. More about MAT: MAT. This tool also provides the details of unreachable objects useful to study the behavior of Garbage Collector.

6. GCViewer
When the Java application is started, it can be asked to dump garbage collector logs using options like –XX:+PrintGCDetails –XX:+PrintGCTimeStamps and -Xloggc:logFile to redirect the logs to a file for further analysis.

GCViewer reads the GC logs to provide a summary of how the garbage collector performed.