如何使用Java中的Powermockito对实用程序类进行单元测试

时间:2017-06-28 22:10:22

标签: java unit-testing powermockito

我已经看过如何通过模拟Static方法来单元测试使用Utility类的类,但是我还没有弄清楚如何对实际的Utility类进行单元测试。

这是实用程序类

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();
    }
}

以下是我目前为单元测试所尝试的内容

@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();
    }
}

如何模拟这样的实用程序类?

1 个答案:

答案 0 :(得分:0)

使用评论中的建议我测试了预期的结果。

    @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);
    }
}