Mockito方法,如果测试

时间:2016-12-21 11:03:35

标签: java mockito

我对测试Mockito有疑问。 我承认我不懂Mockito。 我读了很多页面,我读了很多例子,但仍然没有。

我在Maven有一个程序。我定义了文件名。显示文件的内容。 该程序是:App(条件和显示),methodApp(方法)。

应用

public static void main(String[] args) throws IOException {
    new App();
}
private App() throws IOException {
    methodApp ViewProgram = new methodApp();
    if (ViewProgram.file == null) {
        out.println("No File!");
        return;
    }
    out.println(ViewProgram.removeSpacesDisplaysContents());
}

methodApp

InputStream file = getClass().getResourceAsStream("/"+enterNameFileConsole());

private String enterNameFileConsole(){
    out.println("Enter filename:");
    try {
        return new BufferedReader(new InputStreamReader(System.in)).readLine();
    } catch (IOException e) {
        out.println("Error reading file!");
    }
    return enterNameFileConsole();
}

String removeSpacesDisplaysContents() {
    try {
        return deleteWhitespace(new BufferedReader(new InputStreamReader(file)).readLine());
    } catch (IOException e) {
        out.println("Error reading file!");
    }
    return removeSpacesDisplaysContents();
}

我必须测试App(),enterNameFileConsole()和removeSpacesDisplaysContents()。

如果有人可以提出并解释或想法,如何使用Mockito测试方法和条件。

如果重复该主题,请提供帮助和抱歉。

1 个答案:

答案 0 :(得分:1)

与文件系统或命令行的交互很难直接测试。我通常将它们提取到一个单独的类或方法中,并将该类/方法的行为用于测试。

例如:

import java.io.IOException;
import java.io.PrintStream;

public class App {

    private PrintStream out;
    private InputReader inputReader;

    public App() {
        this(System.out, new InputReader());
    }

    // constructor injection used by tests
    public App(PrintStream out, InputReader inputReader) {
        this.out = out;
        this.inputReader = inputReader;
    }

    public void execute() throws IOException {
        if (inputReader.determineFile()) {
            out.println(inputReader.removeSpacesDisplaysContents());
        } else {
            out.println("No File!");
        }
    }


    public static void main(String[] args) throws IOException {
        App siema = new App();
        siema.execute();
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static java.lang.System.out;

public class InputReader {

    private InputStream in;
    private InputStream file;

    public InputReader() {
        this(System.in);
    }

    // constructor injection used by tests
    public InputReader(InputStream in) {
        this.in = in;
    }

    public boolean determineFile() {
        out.println("Enter filename:");
        try {
            file = getResource("/" + readLine(in));
            return true;
        } catch (IOException e) {
            out.println("Error determining file!");
            return false;
        }
    }

    public String removeSpacesDisplaysContents() throws IOException {
        return deleteWhitespace(readLine(file));
    }

    private String deleteWhitespace(String input) {
        return input.replaceAll("\\s+", "");
    }

    // to be overridden in tests
    InputStream getResource(String name) throws IOException {
        return getClass().getResourceAsStream(name);
    }

    // to be overridden in tests
    String readLine(InputStream is) throws IOException {
        return new BufferedReader(new InputStreamReader(is)).readLine();
    }

}

测试App:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.IOException;
import java.io.PrintStream;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class AppTest {

    private App instance;
    @Mock
    private PrintStream out;
    @Mock
    private InputReader inputReader;

    @Before
    public void setUp() {
        instance = new App(out, inputReader);
    }

    @Test
    public void testExecute() throws IOException {
        //SETUP
        when(inputReader.determineFile()).thenReturn(true);

        String expectedResult = "test result";
        when(inputReader.removeSpacesDisplaysContents()).thenReturn(expectedResult);

        // CALL
        instance.execute();

        // VERIFY
        verify(out).println(expectedResult);
    }

    @Test
    public void testExecuteCannotDetermineFile() throws IOException {

        // SETUP
        when(inputReader.determineFile()).thenReturn(false);

        // CALL
        instance.execute();

        // VERIFY
        verify(out).println("No File!");
    }
}

对InputReader的测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.IOException;
import java.io.InputStream;

import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.testng.AssertJUnit.assertEquals;

@RunWith(MockitoJUnitRunner.class)
public class InputReaderTest {

    @Mock
    private InputStream in;

    @Test
    public void testDetermineFile() {
        // SETUP
        InputReader instance = new InputReader(in) {

            @Override
            InputStream getResource(String name) {
                return null;
            }

            @Override
            String readLine(InputStream is) throws IOException {
                return null;
            }
        };

        // CALL
        boolean result = instance.determineFile();

        // VERIFY
        assertTrue(result);
    }

    @Test
    public void testDetermineFileError() {
        // SETUP
        InputReader instance = new InputReader(in) {

            @Override
            InputStream getResource(String name) throws IOException {
                return null;
            }

            @Override
            String readLine(InputStream is) throws IOException {
                throw new IOException();
            }
        };

        // CALL
        boolean result = instance.determineFile();

        // VERIFY
        assertFalse(result);
    }

    @Test
    public void testRemoveSpacesDisplaysContents() throws IOException {
        // SETUP
        final String line = "test result";
        String expectedResult = "testresult";
        InputReader instance = new InputReader(in) {

            @Override
            InputStream getResource(String name) throws IOException {
                return null;
            }

            @Override
            String readLine(InputStream is) throws IOException {
                return line;
            }
        };

        // CALL
        String result = instance.removeSpacesDisplaysContents();

        // VERIFY
        assertEquals(expectedResult, result);
    }

    // the test succeeds if an IOException is thrown
    @Test(expected = IOException.class)
    public void testRemoveSpacesDisplaysContentsError() throws IOException {
        // SETUP
        InputReader instance = new InputReader(in) {

            @Override
            InputStream getResource(String name) throws IOException {
                return null;
            }

            @Override
            String readLine(InputStream is) throws IOException {
                throw new IOException();
            }
        };

        // CALL
        instance.removeSpacesDisplaysContents();
    }
}