Site icon akquinet AG – Blog

Isolated unit testing of Java EE and Spring components

When developing modern Spring or Jakarta EE based applications and micro services there is a need for fine-granular component testing. I.e. you do not want to test your code in a full-blown environment only, because such tests will be slow.

Instead, you might want to write tests at the component level using a mixture of mocked dependencies and real assets like the (in-memory) database.

needle4k is a Kotlin-based relaunch and upgrade of the well-known needle4j framework. It may be used with any JVM-based language and allows to develop modular tests with minimal effort.

Core features

Writing your first test

Given a simple User DAO:

public class UserDao
  private EntityManager entityManager;

  private MetricsService metricsService;

  public List<User> findByName(final String name)

    return entityManager.createNamedQuery(FIND_BY_STREET)
       .setParameter("name", name).getResultList();

You can write a simple test:

@ExtendWith(JPANeedleExtension.class) // JUnit5 extension mechanism used
public class UserDaoTest {
  // Mock object will be created and injected automatically everywhere
  private MetricsService metricsService;

  // Inject components directly into test using standard annotations
  private EntityManager entityManager;

  // Create tested component and inject dependencies into it
  // and its dependent objects
  private UserDao userDao;

  public void testFindByUsername() {
    final User user = new User("demo");
    User userFromDb = userDao.findByName("demo");

For more information please consult the needle4k homepage and take a look at the quick start project.

Exit mobile version