java 使用 void 方法进行 Junit 测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43769465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:42:47  来源:igfitidea点击:

Junit Testing with void method

javajunitvoid

提问by Seeruttun Kervin

I have to create a JUnit test for the following class, but I cannot do the test for the method deposit.

我必须为以下类创建一个 JUnit 测试,但我无法对方法进行测试deposit

public class Account {
    private int balance;
    private float Interest_Rate =10;

    public Account() {
        this.balance = 0;
    }
    public void deposit(int amount) {       
        balance = balance+amount;
    }
}

@Test
public void testdeposit() {
    Account i = new Account();
    assertEquals("Result",75,i.deposit(25));
}

回答by davidxxx

You could add a getBalance()method in the Accountclass :

您可以getBalance()Account类中添加一个方法:

 public int getBalance(){
      return balance;
    }

And use it to do the assertion :

并用它来做断言:

@Test
public void deposit(){
    Account i = new Account();
    i.deposit(25)
    assertEquals("Result",25, i.getBalance());
}

Generally adding methods that are only used during unit testing may be evaluated and discussed.
But here getBalance()appears as unavoidable.

通常可以评估和讨论添加仅在单元测试期间使用的方法。
但这里getBalance()似乎是不可避免的。

回答by Bor Laze

Testing private fields/methods does not have sense.

测试私有字段/方法没有意义。

In your case, balanceis 'write-only' variable; it should have public accessor (as written above), or field should be used in other methods like

在您的情况下,balance是“只写”变量;它应该具有公共访问器(如上所述),或者应该在其他方法中使用字段,例如

public int income() {
  if(balance == 0 ) return 0;
  if(balance < 100) return 10;
  if(balance < 1000) return 15;
  return 20;
}

In this case your test should be like

在这种情况下,您的测试应该类似于

@Test
public void deposit(){
  Account acc = new Account();
  acc.deposit(150);
  assertEquals("Result ", 15, acc.income());
}

Don't test implementation; test interface.

不要测试实现;测试界面。

回答by NachoGobet

You could have a System.out.println in the method and tell the JUnit test to ask for stdout:

您可以在方法中有一个 System.out.println 并告诉 JUnit 测试请求 stdout:

private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

and then

接着

@Before
public void setUpStreams() {
    System.setOut(new PrintStream(outContent));
}

@After
public void cleanUpStreams() {
    System.setOut(null);
}

finally

最后

assertEquals(<here goes your expected string>, outContent.toString());