DJoke
DJoke

Reputation: 3

How to test a function that returns a string, but has no inputs in Java

So I'm new in java and in testing and I keep trying to test this function but i could not find a way. Any test goes. The function is part of bigger class called SignUp, that has other methods aswell. I know its not very well done :)

public static String newDayOfBirth() {
        Scanner scanner = new Scanner(System.in);
        String dayOfBirth = scanner.nextLine();
        if(Integer.parseInt(dayOfBirth) > 0 && Integer.parseInt(dayOfBirth) < 32){
            return dayOfBirth;
        }
        else {
            System.out.println("Eneter a valid day of birth");
            dayOfBirth = scanner.nextLine();
            return dayOfBirth;
        }
    }

Upvotes: 0

Views: 710

Answers (3)

0xh3xa
0xh3xa

Reputation: 4857

You can mock Scanner using PowerMocktio using

@PrepareForTest({
TargetClass.class,
Scanner.class
})
@RunWith(PowerMockRunner.class)
public class Test {

   private TargetClass target;

   @Before
   public void setUp() {
      target = new TargetClass();
   }

   @Test
    public void shouldDoSomething() {
      // Arrange
      whenNew(Scanner.class).withAnyArgument().thenReturn(mockedScanner);
      when(scanner.nextLine()).thenReturn("line");

      // Act
      String actual = target.newDayOfBirth();

      // Assert
      assertEquals("line", actual);
    }
}

Upvotes: 0

Chris
Chris

Reputation: 1804

The problem is that there is a scanner involved. You really need to split out the handling of input from System.in to somewhere else and change this method to take that text as input and parse and validate that input.

Restrict methods to one piece of behaviour in order to unit test them and isolate behaviour that can't be unit tested (eg handling manual input from system.in) and cover that in integration tests.

Upvotes: 2

akapulko2020
akapulko2020

Reputation: 1139

You'd want to invoke it in the test and then check validity of response ( what is a valid date of birth? Any valid date? One with age more than X?)

Upvotes: 0

Related Questions