我想对下面没有返回值的 ForecastDisplay 类进行 JUnit 测试。此类的工作方式是 currentPressure=29.92f 被测试器类中分配的新压力所取代。 display 方法比较新旧压力并将适当的消息打印到控制台。由于这是一个 void 方法,我不知道如何测试它。
例如:如果我在 JUnit 测试中分配一个新的 currentPressure 为 35,那么第一条消息将打印出来,因为 35>29.92。如果有人可以建议如何对此进行测试,我将不胜感激,因为到目前为止,如果不更改显示方法以返回一个值,我就无法做到这一点,这是作弊,因为我不必调整代码来通过 JUnit 测试。谢谢
public class ForecastDisplay implements Observer, DisplayElement {
private float currentPressure = 29.92f;
private float lastPressure;
private WeatherData weatherData;
public ForecastDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temp, float humidity, float pressure) {
lastPressure = currentPressure;
currentPressure = pressure;
display();
}
public void display() {
System.out.print("Forecast Display: ");
if (currentPressure > lastPressure) {
System.out.println("Improving weather on the way!");
} else if (currentPressure == lastPressure) {
System.out.println("More of the same");
} else if (currentPressure < lastPressure) {
System.out.println("Watch out for cooler, rainy weather");
}
}
}
最佳答案
就目前而言,您需要像 PowerMock
这样的工具模拟 System.out
以确定该方法尝试打印的内容。如何打破处理消息(需要测试)和显示的问题。
public String determineMessage() {
String msg = "Forecast Display: ";
if (currentPressure > lastPressure) {
msg += "Improving weather on the way!";
} else if (currentPressure == lastPressure) {
msg += "More of the same";
} else if (currentPressure < lastPressure) {
msg += "Watch out for cooler, rainy weather";
return msg;
}
public void display() {
System.out.println(determineMessage());
}
这样可以通过对类设置各种压力并断言消息已正确确定来完成单元测试。
关于java - 如何对没有返回值但写入 System.out 的方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067916/