not logged in | [Login]

Java unit testing cookbook

Configure Tests for Mockito

Option 1

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;

@RunWith(MockitoJUnitRunner.class)
public class SomeClass {
 ...
}

Option 2

import org.mockito.MockitoAnnotations;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

Capture arguments with Mockito

@Captor
private ArgumentCaptor<SomeObject> myCaptor;

@Test
public void myTest(){
    ...
    verify(myMock).someMethod(myCaptor.capture());
    assertEquals("something", myCaptor.getValue().getSomething());
}

Mock static methods

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class MyUnitTestClass {
     @Test
	 public void testMyMethodWithStatics() {
		PowerMockito.mockStatic(ClassWithStatics.class);
		
		when(ClassWithStatics.SomeStaticMethod("xyz").thenReturn(someMock);
	 }
}

Mock out "new" instances

Pay close attention to the @PrepareForTest. See http://stackoverflow.com/questions/25317804/using-powermockito-whennew-is-not-getting-mocked-and-original-method-is-called

For example, if the method under test "news" up a new Something (Something mySomething = new Something()), that can be mocked out.

@RunWith(PowerMockRunner.class)
@PrepareForTest({Helper.class, Something.class})
public class HelperTest {
  @Mock
  private Something mockSomething;
      
  @InjectMocks
  private Helper helper;
      
  @Test
  public void doSomething() throws Exception {
      String argument = "arg";
          
      PowerMockito.whenNew(Something.class).withArguments(argument).thenReturn(mockSomething);
          
      helper.doSomething(argument);
          
      verify(mockSomething).doIt();
  }
  
}

Programmatically Logging to the console

Log4j2

LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
loggerConfig.setLevel(Level.INFO);

TODO: Look into PatternLayout.createDefaultLayout()

Log4j1

org.apache.log4j.Logger.getRootLogger().getLoggerRepository().resetConfiguration();
org.apache.log4j.ConsoleAppender console = new org.apache.log4j.ConsoleAppender();
console.setLayout(new org.apache.log4j.PatternLayout(org.apache.log4j.PatternLayout.TTCC_CONVERSION_PATTERN));
console.setThreshold(org.apache.log4j.Level.DEBUG);
console.activateOptions();
org.apache.log4j.Logger.getRootLogger().addAppender(console);