3

I can't figure out how to test this. Tell me please good literature or vebinar on this topic

public InputMessenger getInputForMessengerFromConsole() {
    String templateValue;
    Map<String, String> valuesForTemplate = new HashMap<>();
    try (Scanner scanner = new Scanner(System.in, Constant.CHARSET_NAME_UTF_8)) {
        System.out.println(Constant.MESSAGE_INPUT_TEMPLATE);
        templateValue = scanner.nextLine();

        System.out.println(Constant.MESSAGE_NUMBER_OF_VALUES);
        int numberOfValues = scanner.nextInt();
        scanner.nextLine();

        IntStream.range(0, numberOfValues).forEach(index -> {
            System.out.println(Constant.MESSAGE_KEY + (index + Constant.INT_ONE) + Constant.COLON);
            String key = scanner.nextLine();
            System.out.println(Constant.MESSAGE_VALUE + (index + Constant.INT_ONE) + Constant.COLON);
            String value = scanner.nextLine();
            valuesForTemplate.put(key, value);
        });
    }
    return new InputMessenger(templateValue, valuesForTemplate);
}
  • Can you please elaborate your question. So that the community members could understand the problem precisely. –  Aug 24 '21 at 15:00
  • @JesvinVijeshS I need to write a test for a given method using the Spock framework but I can't figure it out. Could you please help me with this? Maybe you can suggest some literature or how this can be implemented – Trak Polisi Aug 24 '21 at 15:33
  • Have you tried the official Spock manual for starters? If you study it, you should be able to learn everything you need to know about how to test your code. Besides, this kind of question looking for book or website recommendations is off topic here on SO. – kriegaex Aug 24 '21 at 15:58
  • You should probably look into breaking down the method into smaller methods that can then be easily tested. – Leonard Brünings Aug 24 '21 at 16:25
  • @LeonardBrünings Do not tell me, but how can you even mock at the scanner. I mean, how to pass the value in the test to the console? – Trak Polisi Aug 24 '21 at 21:31
  • @TrakPolisi check this https://stackoverflow.com/questions/6415728/junit-testing-with-simulated-user-input and write java code in groovy style for spock testing – centrumek Aug 24 '21 at 21:34

1 Answers1

0

This is a draft (I didn’t check it):

setup: 
def originalIn = System.in
def originalOut = System.out

and: "Define new out:"

def out = new ByteArrayOutputStream()
System.setOut(new PrintStream(out))

and: "Define input data and specify in"

def input = "…input data for test…"
def in = new ByteArrayInputStream(input.getBytes())
System.setIn(in)

when:
def result = getInputForMessengerFromConsole()

then:
out.toString() == expectedOutput

and:
result == expectedResult

cleanup:
System.setOut(originalOut)
System.setIn(originalIn)
Jegors Čemisovs
  • 608
  • 6
  • 14