gpt4 book ai didi

java - 如何从测试类访问私有(private)方法

转载 作者:行者123 更新时间:2023-12-02 06:35:51 28 4
gpt4 key购买 nike

我有一些在类示例中是私有(private)的方法,我想在测试类中使用它们来进行测试,我如何访问这些方法并将它们保留为私有(private)

import java.util.*;

public class Example
{
Scanner scanner;
public Example()
{
scanner = new Scanner(System.in);
}
private void enterName()
{
System.out.println("Enter name");
String name = scanner.nextLine();
System.out.println("Your name is: " + name);
}
private void enterAge()
{
System.out.println("Enter age");
int age = scanner.nextInt();
System.out.println("Your age is : " + age);
}
public void userInput()
{
enterAge();
enterName();
}
}


public class Test
{

public static void main(String args[])
{
Example n = new Example();
n.enterName();
n.enterAge();
}

}

最佳答案

为什么要测试私有(private)方法而只使用公共(public)方法?单元测试是关于测试预期行为。公共(public)方法公开了该行为。

如果您想测试生成的输出,您可以实现一个 protected 方法来写入out,例如

public class Example {

// code omitted

private void enterName() {
writeMessage("Enter name");
String name = scanner.nextLine();
writeMessage("Your name is: " + name);
}

protected void writeMessage(String msg) {
System.out.println(msg);
}
}

在您的测试中,您可以创建一个扩展示例的私有(private)类并覆盖writeMessage方法。

public class ExampleTest {

public testOutput() {
MyExample e = new MyExample();
e.userInput();

String output = e.getOutput();

// test output string
}

private class MyExample extends Example {
private String output = "";

public String getOutput() {
return output;
}

@Override
public void writeMessage(String msg) {
output += msg;
}
}
}

您可能还需要一个可以注入(inject) Scanner 对象的 setter 或构造函数。这将使测试变得更容易,因为您可以注入(inject)模拟的扫描仪版本。

关于java - 如何从测试类访问私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19666353/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com