Search code examples
javaunit-testingpowermockito

How to Unit Test a Utility Class with Powermockito in Java


I've seen how to unit test classes that use Utility classes by mocking the Static method, but I haven't been able to figure out how to unit test the actual Utility Class.

Here is the Utility Class

public class DbNameContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public static void setDbName(String dbName){
        contextHolder.set(dbName);
    }

    public static String getDbName(){
        return (String) contextHolder.get();
    }

    public static void clearDbName(){
        contextHolder.remove();
    }
}

Here is what I've tried so far for a unit test

@RunWith(PowerMockRunner.class)
@PrepareForTest({DbNameContextHolder.class, ThreadLocal.class})
public class DbNameContextHolderTest {
    @SuppressWarnings("rawtypes")
    @Mock
    ThreadLocal threadLocalMock;

    @Before
    public void init() throws Exception{
        PowerMockito.whenNew(ThreadLocal.class).withNoArguments().thenReturn(threadLocalMock);

    }

    @Test
    public void setsDBName(){
        DbNameContextHolder.setDbName("someName");
        verify(threadLocalMock).set("someName");
    }

    @Test
    public void getsDbName(){
        DbNameContextHolder.getDbName();
        verify(threadLocalMock).get();
    }

    @Test
    public void clearsDBName(){
        DbNameContextHolder.clearDbName();
        verify(threadLocalMock).remove();
    }
}

How do I mock a utility class like this?


Solution

  • Using the suggestions in the comments I've tested the expected outcome.

        @RunWith(MockitoJUnitRunner.class)
        public class DbNameContextHolderTest {
    
        @Test
        public void setsAndGetsDBNameCorrectly(){
            DbNameContextHolder.setDbName("someName");
            String returnedName = DbNameContextHolder.getDbName();
            assertEquals("someName",returnedName);
        }
    
        @Test
        public void clearsDBName(){
            DbNameContextHolder.setDbName("someName");
            String returnedName = DbNameContextHolder.getDbName();
            assertEquals("someName",returnedName);
            DbNameContextHolder.clearDbName();
            returnedName = DbNameContextHolder.getDbName();
            assertNull(returnedName);
        }
    }