需要帮助测试 java 中的方法

Need help testing a method in java

我有以下代码:

for (empCount =0 ; empCount < NUMBEROFEMPLOYEES; empCount = empCount + 1)   
{
    System.out.println("Ref NO: " + spRefNo[empCount] + "  \tSalespersons Name:  " + 
    spName[empCount]);
    System.out.println("..............................................."); 
    System.out.println("Type in the salespersons monthly sales");
    System.out.println("...............................................");
    spMonthlySales[empCount]=InOut.readDouble();


    //If to calculate sales persons monthly sales over 10000 pounds
    if (spMonthlySales[empCount]>=10000)
    { 
        spCommission [empCount] = (spMonthlySales [empCount] * (HIGHCOMRATE/100));
        spGrossPay [empCount] = STAFFBASIC + spCommission [empCount];
        spDeductions [empCount] = (spGrossPay [empCount] * (DEDUCTIONSPERCENTAGE/100));
        spNettPay [empCount] = (spGrossPay [empCount] - spDeductions [empCount]);
    }
}

我正在寻求在 JUnit 中为此代码编写测试的帮助 - 我知道如何测试计算出的值,但我不知道如何模拟该方法要求的用户输入。代码大部分是无关紧要的,我还不担心如何测试它,我认为这只是我需要在测试中模拟的用户输入。任何人都可以帮助我解决这个问题,或者指出正确的方向以找到答案吗?

我建议重写函数以获取类似 Scanner 对象 (javadoc) 的内容。您可以在生产代码中对 System.in 使用 Scanner,并在测试中对 String 对象(例如 Scanner sc = new Scanner("This is a test string"))使用 Scanner

您可以使用 System Rules 库提供输入和测试输出。

public class YourTest {
  @Rule
  public SystemOutRule log = new SystemOutRule().enableLog();
  @Rule
  public TextFromStandardInputStream systemInMock = emptyStandardInputStream();

  @Test
  public void test() {
    systemInMock.provideLines("first", "second");
    ... //execute your code
    assertEquals("First!\nSecond!\n", log.getLogWithNormalizedLineSeparator());
  }
}

完全披露:我是系统规则的作者。