Unit Testing: How My Approach Differs from Yours

The article walks through a step‑by‑step evolution of a simple isEmpty utility, demonstrates proper JUnit assertions, introduces Mockito for isolating complex service logic, and explains Spring Boot Test components, illustrating why thorough unit testing saves time and improves code quality.

Architect's Journey
Architect's Journey
Architect's Journey
Unit Testing: How My Approach Differs from Yours

Jensen introduces the topic by questioning whether writing unit tests is a waste of time under project pressure and promises to show his perspective through concrete examples.

0x1 – Evolution of a simple utility

Starting with a naive implementation that only checks for null:

public static boolean isEmpty(String str) {
    return str == null;
}

He writes a main method to print the result for null and a non‑empty string. When the product later requires the method to reject empty strings, he updates the code:

public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
}

He adds tests for "". The next day the product adds a rule that a single space is also invalid, leading to:

public static boolean isEmpty(String str) {
    return str == null || str.length() == 0 || Objects.equals(" ", str);
}

Finally, to reject any amount of whitespace, he rewrites the method with a loop:

public static boolean isEmpty(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(str.charAt(i))) {
            return false;
        }
    }
    return true;
}

Each change is verified with a main method that prints the outcome for various inputs, illustrating how vague requirements and ad‑hoc testing can lead to missed scenarios.

0x2 – JUnit basics and assertions

He shows a typical JUnit test that only logs results:

@Test
public void test() {
    boolean result = MyStringUtils.isEmpty(null);
    log.info("result: {}", result); // true
    // ... other cases
}

He then refactors the test to include explicit assertions:

@Test
public void test2() {
    boolean result = MyStringUtils.isEmpty(null);
    log.info("result: {}", result);
    Assert.assertTrue(result);
    // ... other cases with Assert.assertTrue/False
}

He also demonstrates timeout and expected‑exception tests with @Test(timeout = 2000) and @Test(expected = ArithmeticException.class).

0x3 – Why Mockito matters

In Spring Boot services, dependencies such as databases, caches, and message queues make pure JUnit tests slow and prone to dirty data. He argues that unit tests should focus on core algorithms, complex business logic, and idempotent requirements, and that splitting a large service method into smaller, mockable units improves test speed and fault isolation.

He presents a personal efficiency formula: time spent writing and using unit tests < time spent debugging integration failures .

0x4 – Mockito example for a permission check

He provides a private method isUserRight that decides whether a user has permission. Using PowerMock and Mockito, he mocks static utilities, creates test data, invokes the private method via reflection, and asserts three scenarios: no permission, direct permission, and role‑based permission mismatch.

private boolean isUserRight(String service, String path, String requestMethod, CacheGatewayUseDTO gatewayUse) {
    if (isDirectUserRight(gatewayUse.getUserRights(), service, path, requestMethod)) {
        return true;
    }
    return isUserRoleRight(service, path, requestMethod, gatewayUse.getRoleIds());
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(CacheUtils.class)
public class PowerFilterTest {
    @InjectMocks
    private PowerFilter powerFilter;
    // ... fields omitted for brevity
    @Test
    public void isUserRight() throws Exception {
        PowerMockito.mockStatic(CacheUtils.class);
        PowerMockito.when(CacheUtils.notExistNewRole(ArgumentMatchers.anyLong())).thenReturn(false);
        // build role, rights, gatewayUse, etc.
        Method method = PowerMockito.method(PowerFilter.class, "isUserRight",
                String.class, String.class, String.class, CacheGatewayUseDTO.class);
        // invoke and assert results for different paths
    }
}

0x5 – Spring Boot Test overview

The spring-boot-starter-test bundle includes:

JUnit – the core unit‑testing framework (default 4.12).

Spring Test & Spring Boot Test – support for loading Spring contexts.

AssertJ – fluent assertions.

Hamcrest – matcher library.

Mockito – mocking framework.

JSONassert – JSON assertions.

JsonPath – JSON path queries.

He lists the

@SpringBootTest
webEnvironment

options (MOCK, RANDOM_PORT, DEFINED_PORT, NONE) with brief descriptions.

0x6 – Summary

Even with only 30 % of unit‑testing knowledge, the author finds that proper tests improve code quality, shorten integration cycles, and enable rapid problem localisation. He encourages readers to value unit testing and continue learning.

Javaunit testingJUnitMockitotest best practicesSpring Boot Test
Architect's Journey
Written by

Architect's Journey

E‑commerce, SaaS, AI architect; DDD enthusiast; SKILL enthusiast

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.