【问题标题】:How to test method without args using the spock framework如何使用 spock 框架测试没有 args 的方法
【发布时间】:2021-10-24 11:41:35
【问题描述】:

我不知道如何测试这个。请告诉我有关此主题的优秀文献或讨论

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

【问题讨论】:

  • 您能否详细说明您的问题。以便社区成员能够准确理解问题。
  • @JesvinVijeshS 我需要使用 Spock 框架为给定方法编写一个测试,但我无法弄清楚。你能帮我解决这个问题吗?也许您可以建议一些文献或如何实施
  • 你试过Spock官方的初学者手册吗?如果你学习它,你应该能够学习关于如何测试你的代码所需要知道的一切。此外,这种寻找书籍或网站推荐的问题在 SO 上是题外话。
  • 您可能应该考虑将方法分解为可以轻松测试的更小方法。
  • @LeonardBrünings 不要告诉我,但你怎么能嘲笑扫描仪。我的意思是,如何将测试中的值传递给控制台?

标签: java spock


【解决方案1】:

这是草稿(我没查):

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多