java - 如何对没有返回值但写入 System.out 的方法进行单元测试

标签 java junit

我想对下面没有返回值的 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/

相关文章:

java - 如何为 Spring Boot 应用程序执行命令行任务(如 Rake 任务)?

java - 关于JUnit的疑问和建议

spring - 如何模拟 POST 参数和模型属性?

java - 如何将每个单词另起一行?

java - 无法使用 Spring Social 创建 LinkedIn Controller bean

java - Gradle - jacoco 任务在 Spring 应用程序运行时添加合成字段,导致计算类中已声明字段数量的测试失败

junit - 如何使用 Ant 执行 JUnit 5 @Tag 测试?

java - 如何设置 JUnit 测试的日志级别

java - 生成Android签名应用时出错

java - 如何使用 Java/Scala 从 URL 加载前 x 个字节?