Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test method without args using the spock framework

Tags:

java

spock

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);
}
like image 490
Trak Polisi Avatar asked Jul 20 '26 00:07

Trak Polisi


1 Answers

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)
like image 199
Jegors Čemisovs Avatar answered Jul 21 '26 13:07

Jegors Čemisovs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!