简体   繁体   English

Java IO,输入流和输出流测试

[英]Java IO, inputstream and Outputstream testing

I am trying to create a simple chat program.我正在尝试创建一个简单的聊天程序。
Initially I wrote this code to save an input message from user into a Text file, depending on the given Command, but I don't have any idea about the testing strategy.最初,我编写此代码以根据给定的命令将来自用户的输入消息保存到文本文件中,但我对测试策略一无所知。 Should I write test for the runUi() only?我应该只为runUi()编写测试吗? Because this method already contains switch statement and inside it are the other methods invoked, or should I write for all other methods as well?因为这个方法已经包含 switch 语句并且在它里面是调用的其他方法,还是我应该为所有其他方法编写?

public class CmdLineUI implements ChatUI, Chat {
    public static final String WRITE = "write";
    public static final String READ = "read";
    public static final String EXIT = "exit";
    public static final String ERRORMESSAGE = "unknown command";

    private final PrintStream consoleOutput;
    private final BufferedReader userInput;

    public CmdLineUI(PrintStream os, InputStream is) {
        this.consoleOutput = os;
        this.userInput = new BufferedReader(new InputStreamReader(is));
    }

    public static void main(String[] args) throws Exception {
        PrintStream os = System.out;
        os.println("***Welcome to The ChatSystem:  input: write for chatting ,"
                + "\n    for Reading the messages input: read ,for closing Chat input: exit ***");

        CmdLineUI userCmd = new CmdLineUI(os, System.in);

        userCmd.runUi(System.in, os);
    }



    private String[] readCommands() throws Exception {
        String[] result = new String[1];
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String commandLinString = null;
        String command = null;

        try {
            System.out.println("> ");

            commandLinString = br.readLine();
            StringTokenizer st = new StringTokenizer(commandLinString);
            command = st.nextToken().trim();
            // msg = st.nextToken();

            System.out.println("command :" + command);
        } catch (IOException e) {
            System.out.println("Exception when reading from comman line" + e.getLocalizedMessage());
        }
        result[0] = command;
        // result[1] = msg;

        return result;
    }

    @Override
    public void writeMessage(String message) throws Exception {
        System.out.println("Start with Writing mood:");

        try {
            File file = new File("/home/sami/Desktop/file.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(System.in); // A stream for reading from the
                                                                                    // console
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // Connect InputStreamReader to a
                                                                                    // BufferedReader
            FileWriter fileReader = new FileWriter(file); // A stream that connects to the text file
            BufferedWriter bufferedWriter = new BufferedWriter(fileReader); // Connect the FileWriter to the
                                                                            // BufferedWriter
            String line;
            boolean continuee = true;

            while (!(line = bufferedReader.readLine()).equals("stop")) {
                continuee = false;
                bufferedWriter.write(line);
            }
            // Close the stream
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void readMessage() throws Exception {
        System.out.println("start with reading mood:");

        File file = new File("/home/sami/Desktop/file.txt");
        FileInputStream fileinputstream = new FileInputStream(file);

        try {
            int oneByte;
            while ((oneByte = fileinputstream.read()) != -1) {
                System.out.write(oneByte);
            }

            System.out.flush();
        } catch (Exception ex) {
            ex.getMessage();
        }

        fileinputstream.close();
    }

    @Override
    public void runUi(InputStream inp, OutputStream outp) throws Exception {
        File file = new File("/home/sami/Desktop/file.txt");
        FileReader filereader = new FileReader(file);
        BufferedReader br = new BufferedReader(filereader);

        // CmdLineUI obj = new CmdLineUI(consoleOutput);
        PrintStream ps = new PrintStream(outp);
        boolean again = true;

        while (again) {
            String[] commandMsg = readCommands();
            String command = commandMsg[0];

            switch (command) {
            case WRITE:
                writeMessage(br.readLine());
                again = true;
                break;

            case READ:
                readMessage();
                again = true;
                break;

            case EXIT:    
                again = false;
                break;

            default:
                ps.println(ERRORMESSAGE);
            }
        }

    }

}

and I have created these two interfaces here is the first one我已经创建了这两个接口,这里是第一个

public interface ChatUI {
    public void runUi (InputStream inp, OutputStream outp) throws Exception;
}

the second Interface第二个接口

public interface Chat {
     //First Method 
    public void writeMessage(String message)throws Exception;

    // Second Method
    public void readMessage()throws Exception;
}

Write tests for your runUi() method because in all the other methods, you are either reading from console and tokenizing the input String , writing to a file or reading from a file.为您的runUi()方法编写测试,因为在所有其他方法中,您要么从控制台读取并标记输入String ,要么写入文件,要么从文件读取。 All of these 3 operations have already been tested by folks at Oracle and/or the Java language developers (you can google about this process if you want to know more). Oracle 和/或 Java 语言开发人员已经对所有这 3 个操作进行了测试(如果您想了解更多信息,可以通过谷歌搜索此过程)。

Check to see if your program flow is working as expected and write tests for them and don't bother with the functions where all you are doing is calling come Java API and then doing almost nothing except for returning (or writing to somewhere) from it.检查您的程序流程是否按预期工作并为它们编写测试,并且不要打扰您正在做的所有功能就是调用 Java API 然后除了从它返回(或写入某处)之外几乎什么都不做.

I wrote this program again using different way, and I have tested the Methods also:我用不同的方式再次编写了这个程序,我也测试了这些方法:

import java.io.*;
import java.util.*;

public class CmdLineUI implements ChatUI, Chat {

    public static final String WRITE = "write";
    public static final String READ = "read";
    public static final String EXIT = "exit";
    public static final String ERRORMESSAGE = "unknown command";

    private BufferedReader userInput;

    public static void main(String[] args) throws Exception {
        PrintStream os = System.out;
        os.println("***Welcome to The ChatSystem:  input: write for chatting ,"
                + "\n    for Reading the messages input: read ,for closing Chat input: exit ***");

        CmdLineUI userCmd = new CmdLineUI();

        userCmd.runUi(System.in, System.out);

    }

    @Override
    public void writeMessage(String message) throws Exception {
        System.out.println("Start with Writing mode:");
        try {
            File file = new File("/home/sami/Desktop/file.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(System.in); // A stream for reading from the
                                                                                    // console
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // Connect InputStreamReader to a
                                                                                    // BufferedReader

            FileWriter fileReader = new FileWriter(file); // A stream that connects to the text file
            BufferedWriter bufferedWriter = new BufferedWriter(fileReader); // Connect the FileWriter to the
                                                                            // BufferedWriter

            String line;
            boolean continuee = true;
            while (!(line = bufferedReader.readLine()).equals("stop")) {
                continuee = false;
                bufferedWriter.write(line);
            }

            // Close the stream
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void readMessage() throws Exception {
        System.out.println("start with reading mode:");
        File file = new File("/home/sami/Desktop/file.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));
        try {
            String oneByte;
            while ((oneByte = br.readLine()) != null) {
                System.out.println(oneByte);
            }

        }

        catch (Exception ex) {
            ex.getMessage();
        }

    }

    @Override
    public void runUi(InputStream inp, OutputStream outp) throws IOException {
        this.userInput = new BufferedReader(new InputStreamReader(inp));

        BufferedReader br = new BufferedReader(userInput);
        PrintStream ps = new PrintStream(outp);

        CmdLineUI userCmd = new CmdLineUI();

        String commandLinString = null;
        boolean again = true;
        try {
            while (again) {

                System.out.println("> ");
                commandLinString = br.readLine().trim();
                StringTokenizer st = new StringTokenizer(commandLinString);
                String command = st.nextToken();
                // String msg= userCmd.readCommands(command);
                System.out.println("command :" + command);
                switch (command) {

                case WRITE:

                    writeMessage(command);
                    again = true;
                    break;

                case READ:

                    readMessage();

                    again = true;
                    break;
                case EXIT:

                    again = false;
                    break;
                default:
                    ps.println(ERRORMESSAGE);
                }

            }

        } catch (Exception e) {
            System.out.println("Exception when reading from comman line" + e.getLocalizedMessage());

        }

    }

}

And Here is the Test:这是测试:

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import junit.framework.Assert;

import java.io.*;

class CmdTesting {



    @Test
    void test() throws Exception {
        try {
            CmdLineUI obj = new CmdLineUI();

            InputStream myInputStream = null;

            String unknownCommandString = "hello world";
            String exitString = CmdLineUI.EXIT;

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeUTF(unknownCommandString);

            byte[] inputBytes = baos.toByteArray();

            ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
            myInputStream = bais;

            ByteArrayOutputStream myOutputStream = new ByteArrayOutputStream();

            obj.runUi(myInputStream, myOutputStream);

            ByteArrayInputStream outputIS = new ByteArrayInputStream(myOutputStream.toByteArray());

            DataInputStream dis = new DataInputStream(outputIS);

            dis.readUTF();

            String expected = "hello world";

            assertEquals(expected, unknownCommandString);

        } catch (Exception ex) {
            ex.getLocalizedMessage();
        }

    }

    @Test
    public void writeMessage() throws Exception {

        File file = new File("/home/sami/Desktop/file.txt");
        String str = "Hello";

        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
        writer.append(' ');
        writer.append(str);

        writer.close();
    }


    @Test
    public void reamessage() throws Exception {
        File file=new File("/home/sami/Desktop/file.txt");

        BufferedReader reader = new BufferedReader(new FileReader(file));
        reader.read();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM