如何测试 System.out.println();通过嘲笑 [英] How to test System.out.println(); by mocking

查看:41
本文介绍了如何测试 System.out.println();通过嘲笑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我必须练习如何使用 Mockito 谁能告诉我我们如何使用模拟对象来测试基于控制台的输出测试,例如

hello I have to practice how to use Mockito can someone please tell me how do we use mock objects to test the console based output testing for example

Random rand = new Random();
int number = 1+rand.nextInt(100);              // random number 1 to 100
Scanner scan = new Scanner(System.in);

for (int i=1; i<=10; i++){                     // for loop from 1 to 10
    System.out.println(" guess "+i+ ":");``
    int guess = scan.nextInt();
    //if guess is greater than number entered 
    if(guess>number)
        System.out.println("Clue: lower");
    //if guess is less than number entered 
    else if (guess<number )
        System.out.println("lue: Higher");
    //if guess is equal than number entered 
    else if(guess==number) {
        System.out.println("Correct answer after only "+ i + " guesses – Excellent!");
        scan.close();
        System.exit(-1);
    }

}

System.out.println("you lost" + number);
scan.close();

推荐答案

首先 - 调用 System.exit() 会破坏你的测试.

First off - the call to System.exit() will break your test.

第二 - 模拟 System 类不是一个好主意.将 System.out 重定向到伪造或存根更有意义.

Second - not a good idea to mock the System class. It makes more sense to redirect System.out to a fake or stub.

第三 - 从 System.in 中读取内容在测试中也很棘手.

Third - Reading stuff from System.in will be tricky to do from test as well.

除此之外:我冒昧地减少了代码的可读性:

Apart from that: I've taken the liberty to reduce the code for readability:

public class WritesOut {

    public static void doIt() {
           System.out.println("did it!");
    }

}

测试应该测试 Line 是否被打印到 System.out:

Test should test if Line was printed to System.out:

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.Test;

public class WritesOutTestUsingStub {

    @Test
    public void testDoIt() throws Exception {
        //Redirect System.out to buffer
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        System.setOut(new PrintStream(bo));
        MockOut.doIt();
        bo.flush();
        String allWrittenLines = new String(bo.toByteArray()); 
        assertTrue(allWrittenLines.contains("did it!"));
    }

}

这篇关于如何测试 System.out.println();通过嘲笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆