天天看點

Java如何編寫無傳回值的方法的單元測試

有一個方法,他的傳回值是void也就是說,我們無法對方法的傳回值進行斷言。

但是,既然這個方法是無傳回值的方法,那麼他一定修改了對象的狀态(成員變量),或是進行了輸入輸出,向某個視窗發送消息,與某個程序通訊,

總之,他是有副作用的。

如果沒有任何副作用,并且無傳回值,那麼這個方法存在也是沒有意義的,可以去掉。

那麼我們就可以針對産生的副總用來進行斷言。

舉一個例子

待測試的類

public class HowHandleVoidMethodJUnit {
    private String name = "helloworld";

    public void voidMethod() {
        this.name = "一個傳回void的方法如何進行測試???";
    }
}
           

測試類

import org.junit.Test;

import java.lang.reflect.Field;

import static org.junit.Assert.*;

public class HowHandleVoidMethodJUnitTest {
    @Test
    public void testVoidMethod() throws Exception {
        HowHandleVoidMethodJUnit howHandleVoidMethodJUnit = new HowHandleVoidMethodJUnit();
        Class<?> clazz = howHandleVoidMethodJUnit.getClass();
        Field field = clazz.getDeclaredField("name");
        field.setAccessible(true);
        String string = (String) field.get(howHandleVoidMethodJUnit);

        assertEquals("helloworld", string);
        howHandleVoidMethodJUnit.voidMethod();

        String string1 = (String) field.get(howHandleVoidMethodJUnit);
        assertEquals("一個傳回void的方法如何進行測試???",string1);
    }

}
           

在被測方法的前後,我們去斷言成員變量的值,也就是對象的狀态。