天天看点

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

}
           

在被测方法的前后,我们去断言成员变量的值,也就是对象的状态。