简体   繁体   中英

Test void method with JUnit

Let's say I have a class like this one:

public class MyClass {

   private int var1;
   private int var2;

   public MyClass() {
      var1 = 0;
      var2 = 0;
   }

   public void setVariables() {
      var1 = 1;
      var2 = 1;
   }

I don't have any getter method inside my class.

Is there a way to test a void method like setVariables() with JUnit? How can I check its behavior without a direct access to variables value?

Since this method does not have visible (from outside) side effect I would probably not test it.

Presumably, the fact that you set those variables has side effects on other methods. That's where you can test that those other methods execute as expected.

您可以使用反射来访问变量,以groovy编写测试用例,从而允许您动态添加getter方法,可以使用某种AOP风格(cglib,aspectJ)来测试该方法的调用。

setVariables from your example is too simple to test. if your real method have any visible effects (non private state) then test that state. if state is private but has influence on other methods then test this method together with other methods. if you feel setVariables is so complex that it should be tested separately then test it. but remember: at this stage you are testing implementation, not the external contract - you will have to change your tests when you change implementation. if you want to do it, i suggest make var1 and var2 package visible - it's very convenient for tests. if they must stay private then the only solution is reflection and libraries like whiteBox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM