junit testing for user input using Scanner

前端 未结 4 878
终归单人心
终归单人心 2020-12-06 01:04

I have to test a method in a class which takes an input using Scanner class.

package com.math.calculator;

import java.util.Scanner;

public class InputOutpu         


        
4条回答
  •  时光取名叫无心
    2020-12-06 01:48

    You can write a clear test for the command line interface by using the TextFromStandardInputStream rule of the System Rules library.

    public void MyTest {
      @Rule
      public final TextFromStandardInputStream systemInMock
        = emptyStandardInputStream();
    
      @Test
      public void shouldTakeUserInput() {
        systemInMock.provideLines("add 5", "another line");
        InputOutput inputOutput = new InputOutput();
        assertEquals("add 5", inputOutput.getInput());
      }
    }
    

提交回复
热议问题