【发布时间】:2017-05-08 23:06:50
【问题描述】:
我在理解 Mockito 的概念时遇到了一些麻烦。我编写了一个小程序来提供帮助,但我无法让它做我想做的事情。
这是我的代码:
// WeatherDemo.java:
package com.abc;
public class WeatherDemo {
public String getForecast() {
// Get the high remperature for today, and return back to the caller one of these values:
// cold, mild, or hot
// cold will be returned if the high temp is forecast to be less than 60.
// hot will be returned if the high temp is forecast to be more than 79.
// Otherwise, mild will be returned (this indicates a high temp in the 60s or 70s).
int highTemp = getHighTemp();
if (highTemp < 60)
return("cold");
if (highTemp > 79)
return("hot");
return("mild");
}
public int getHighTemp() {
// Because this is a demo, we don't have access to any source (web service, DB, etc.) to get the high temp.
// Just hard code a value here, but remember that if this were a real application, we would be dynamically
// retrieving the day's high temperature from some external source.
int highTemp = 32;
return(highTemp);
}
}
================================================ ===================================
// TestWeatherDemo.java:
package com.abc;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import org.junit.Test;
import org.mockito.Mockito;
public class TestWeatherDemo {
@Test
public void testWeatherReport() {
WeatherDemo testMockito = Mockito.mock(WeatherDemo.class);
WeatherDemo testJUnit = new WeatherDemo();
when(testMockito.getHighTemp()).thenReturn(90);
assertEquals("hot", testJUnit.getForecast());
}
}
================================================ ===================================
基本上,我想在 getForecast() 上运行 JUnit。根据当天的高温,它会返回冷、温和或热。要获得高温,它调用 getHighTemp()。让我们假设 getHighTemp() 调用 Web 服务来获取温度(我硬编码一个值只是为了测试目的)。因为这是一个外部资源,所以我的 Junit 没有通过隔离测试,根本就不是真正的单元测试。更不用说 getHighTemp() 每次调用都不会返回相同的值。
因此,我想模拟 getHighTemp(),告诉它始终返回 90 的温度。
Mockito 测试从 testWeatherReport() 运行。这就是我卡住的地方。这样做时,我可以模拟 getHighTemp() 以返回 90:
当(testMockito.getHighTemp()).thenReturn(90);
但是,当从 getForecast() 调用时,我无法让它返回 90。断言变得“冷”,因为它选择的是 32,而不是 90。
Mockito 背后的整个想法不就是我可以模拟一个方法并准确地告诉它要返回什么,以消除外部依赖吗?如果从 getForecast() 调用 getHighTemp() 不会返回 90,我看不出 Mockito 的目的。我在这里想念什么?感谢您的帮助和启发。
比尔
【问题讨论】:
标签: java unit-testing junit mocking mockito