【问题标题】:Mockito method and if testMockito 方法和 if 测试
【发布时间】:2016-12-21 11:03:35
【问题描述】:

我对 Mockito 的测试有疑问。 我承认我不懂 Mockito。 我阅读了很多页面,阅读了很多示例,但仍然一无所获。

我在 Maven 中有一个程序。我定义文件名。显示文件的内容。 程序为:App(condition and display of ),methodApp(methods)。

应用程序

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

方法应用

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 测试方法和条件。

如果主题重复,请帮助并抱歉。

【问题讨论】:

  • 您的程序中有一个无限递归循环,因为方法removeSpacesDisplaysContents 在语句return removeSpacesDisplaysContents(); 中以无限递归循环调用自身。
  • 我尝试更改它,但后来我遇到了输入流问题,没有将文件名提供给存储路径,而是返回时我使用 try ... cry。跨度>
  • 您可能应该首先专注于学习 Java 编程的基础知识,确保您彻底了解类和方法的工作原理,然后再学习更复杂的东西,例如 Mockito。
  • 我不完全同意。 Ziomell 的代码非常规,并且确实有一个可能的无限循环,但对我来说它表明了理解。也许OP是自学的?无论如何,我试图在不过度重构原始代码的情况下回答这个问题。这对我来说是一个相当大的挑战!

标签: java mockito


【解决方案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();
    }

}

应用测试:

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

【讨论】:

  • Adriaan Koster 自己建议的早期问题。现在的问题是,当我给正确的文件名时显示内容,因为它会给出错误的显示错误而不是“无文件”。可能是If的问题?
  • 我更新了 InputReaderTest 的代码,缺少一个模拟。您试图解释的问题发生在运行应用程序或运行测试时?我可能破坏了你的代码,我没有编译或测试它。请澄清到底出了什么问题。
  • 我在邮件上写信给你,邮件在网站上找到。我描述了问题并加入了截图。在这里我无法描述这个问题。谢谢你和最好的问候
  • 我修复了代码。确实有一些错误。最大的一个是 InputReader 中的代码添加了两次“/”。测试中还有一些不正确的大括号和缺少 @RunWith 注释。这就是你在 IDE 之外输入代码时得到的结果:-D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 2017-07-12
  • 2023-02-13
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多