necrofish666
necrofish666

Reputation: 75

Need help testing a method in java

I have the following code:

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

I'm looking help writing a test for this code in JUnit - I know how to test the values that are calculated, but I don't know how to simulate the user input that the method asks for. The code is mostly irrelevant, I'm not worried yet about how to test it, it's just the user input I need to simulate in the test, I think. Anybody able to help me with this, or point me in the right direction to find an answer?

Upvotes: 0

Views: 84

Answers (2)

Stefan Birkner
Stefan Birkner

Reputation: 24510

You could provide input and test output with the System Rules library.

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

Full disclosure: I'm the author of System Rules.

Upvotes: 0

MrHug
MrHug

Reputation: 1315

I would suggest rewriting the function to take something like a Scanner object (javadoc). You can have a Scanner on System.in in your production code, and have a Scanner on a String object (e.g. Scanner sc = new Scanner("This is a test string")) in your tests.

Upvotes: 2

Related Questions