JUnit:cheat sheet

set private static field

org.powermock.reflect.Whitebox.setInternalState(Foo.class, "i", 2);

set private field

org.mockito.internal.util.reflection.Whitebox.setInternalState(foo, "i", 2);

get directory or file relative to the current test case class

import org.springframework.util.ResourceUtils;
File dir =
  ResourceUtils.getFile(this.getClass().getResource("test_01"));
File file =
  ResourceUtils.getFile(this.getClass().getResource("test_01/input.json"));

assert directory equals(useful for tesing file copying)

public static void assertDirectoryEquals(File expectedDir, File actualDir) throws IOException {
  Assert.assertTrue(expectedDir.exists() && expectedDir.isDirectory());
  Assert.assertTrue(actualDir.exists() && actualDir.isDirectory());
  File[] fileAndDirsExpected = expectedDir.listFiles();
  File[] fileAndDirsActual = actualDir.listFiles();
  Assert.assertEquals(fileAndDirsExpected.length, fileAndDirsActual.length);
  for (File expectedFileOrDir : fileAndDirsExpected) {
    if (expectedFileOrDir.isDirectory()) {
      // directory
      assertDirectoryEquals(expectedFileOrDir, new File(actualDir, expectedFileOrDir.getName()));
    } else {
      // file
      Assert.assertTrue(FileUtils.contentEquals(expectedFileOrDir,
          new File(actualDir, expectedFileOrDir.getName())));

    }
  }
}

assert object equals using json

import org.skyscreamer.jsonassert.JSONCompare;
import org.springframework.util.FileCopyUtils;
...
String expectedJson = FileCopyUtils.copyToString(new InputStreamReader(
    testClass.getResourceAsStream(expectedJsonFile), StandardCharsets.UTF_8));
JSONCompareResult cmpResult = JSONCompare.compareJSON(expectedJson, actualJson, JSONCompareMode.LENIENT);
Assert.assertFalse(cmpResult.getMessage(), cmpResult.failed());

prepare database by executing sql(spring test)

import org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener;
...
@TestExecutionListeners({SqlScriptsTestExecutionListener.class})
public class TestFoo {
  @Sql(statements = "ALTER SEQUENCE bar_seq RESTART WITH 1;")
  public void test_bar_01() {
  }
}

customize database config(spring-test-dbunit)

@Configuration
public class DbUnitConfigurations {
  @Bean
  public DatabaseConfigBean databaseConfig() {
    DatabaseConfigBean bean = new DatabaseConfigBean();
    bean.setAllowEmptyFields(true);
    return bean;
  }

  @Bean
  public DatabaseDataSourceConnectionFactoryBean databaseDataSourceConnection(
      DatabaseConfigBean databaseConfig, DataSource dataSource) {
    DatabaseDataSourceConnectionFactoryBean bean = new DatabaseDataSourceConnectionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setDatabaseConfig(databaseConfig);
    return bean;
  }
}

public class ColumnSensingReplacementDataSetLoader extends FlatXmlDataSetLoader {
  @Override
  protected IDataSet createDataSet(Resource resource) throws Exception {
    FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
    builder.setColumnSensing(false);
    FlatXmlDataSet dataSet = builder.build(resource.getURL());
    ReplacementDataSet replacementDataSet = new ReplacementDataSet(dataSet);
    replacementDataSet.addReplacementObject("[null]", null);
    replacementDataSet.addReplacementSubstring("[/n]", "\n");
    return replacementDataSet;
  }
}
@DbUnitConfiguration(dataSetLoader = ColumnSensingReplacementDataSetLoader.class,
    databaseConnection = "databaseDataSourceConnection")
public class TestFoo {
}

get target object from spring bean

  public static Object getTargetObjectFromSpringBean(Object proxy) throws Exception {
    if (AopUtils.isJdkDynamicProxy(proxy)) {
      return ((Advised) proxy).getTargetSource().getTarget();
    } else if (AopUtils.isCglibProxy(proxy)) {
      TargetSource targetSource =
          (TargetSource) ReflectionTestUtils.invokeMethod(proxy, "getTargetSource");
      return targetSource.getTarget();
    } else {
      return proxy;
    }
  }

Capture output

import org.springframework.boot.test.rule.OutputCapture;
  @Rule
  public OutputCapture capture = new OutputCapture();
...
  Assert.assertThat(capture.toString(), Matchers.containsString("some text"));