[英]How to Unit Test a Method that changes data in Java
假设我有如下代码
public boolean checkForecastIfCityRaining(String name){
result = WeatherAPICallToSomeVendor(name)
if(result = rain)return true; else return false;
}
如何根据API供应商提供的内容对结果数据是否进行更改进行单元测试?
我会模拟每种情况的固定结果,然后像这样进行单元测试吗?
UNIT测试实际上应该一次只测试一个方法(隔离可能由该方法调用的其他功能)。 我目前的小组可以通过这样编写我们的函数来实现这一点:
public class WeatherCheck
{
private ForecastService fs;
public WeatherCheck(ForecastService fs)
{
forecastService = fs;
}
public boolean checkForecastIfCityRaining(String name){
result = forecastService.weatherAPICallToSomeVendor(name)
if(result = rain)return true; else return false;
}
这将使我们能够将模拟预测服务传递给构造函数。 依赖注入会更好,但是我们还没有这样做。
注意:我们区分单元测试和集成测试。 我们仍然可以使用Junit编写集成测试,但是它们更倾向于退出并实际戳破服务-这可以给您预先警告失败。 因此,您可以为ForecastService编写集成测试,该测试仅调用ForecastService的weatherAPICallToSomeVendor方法并确保无错误结果(也许没有异常,或者不返回null ...)。
我认为该功能需要这样重写:
public boolean checkForecastInCityCondition(String city, String condition){
result = WeatherAPICallToSomeVendor(city)
return result == condition;
}
现在,您获得了使客户不必担心任意conditions
的优势,并且可以根据需要使用新的API进行增强。 从测试的角度来看,您现在可以安全地编写如下的测试:
public void testRainingInLancaster() throws Exception{
//your code here
}
public void testSnowInRedding() throws Exception{
//your code here
}
您可以确定需要模拟哪些零件进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.