![](/img/trans.png)
[英]How can I test if a class method is calling another method from one of the classes's private objects
[英]how can I access a private method from the test class
我有一些在類示例中是私有的方法,我想在測試類中使用它們進行測試,如何訪問這些方法並將它們保存為私有
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();
}
}
為什么要測試私有方法,而只使用公共方法? 單元測試是關於預期行為的測試。 公共方法暴露了這種行為。
如果你想測試產生的輸出,你可以實現一個受保護的方法寫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);
}
}
在測試中,您可以創建一個擴展Example的私有類,並覆蓋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;
}
}
}
單元測試確實是黑盒測試,因此您不能也不應該訪問私有(內部機制)方法。 但是,白盒測試通常稱為基於斷言的驗證。 只需將斷言(或it-then-throw語句)放在任何地方,您的黑盒單元測試將成為白盒測試。
更具體地說,嘗試在您的私有方法中盡可能多地放置前置條件和后置條件,以驗證輸入和輸出。 因此,您在每個方法調用者和被調用者之間定義一個契約。 如果出現問題,您將很快看到地點和原因。
有關詳細信息,請參閱合同設計 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.