简体   繁体   English

如何对在Java中更改数据的方法进行单元测试

[英]How to Unit Test a Method that changes data in Java

Suppose I have a code like below 假设我有如下代码

public boolean checkForecastIfCityRaining(String name){
    result = WeatherAPICallToSomeVendor(name)
    if(result = rain)return true; else return false;


}

How would I unit test if the result data will change depending on what the API vendor is providing? 如何根据API供应商提供的内容对结果数据是否进行更改进行单元测试?

Would i mock a fixed result of every scenario and then unit test it like so? 我会模拟每种情况的固定结果,然后像这样进行单元测试吗?

A UNIT test should really only test a single method at a time (Isolate other functionality that might be invoked by that method). UNIT测试实际上应该一次只测试一个方法(隔离可能由该方法调用的其他功能)。 My current group might achieve that by writing our function like this: 我目前的小组可以通过这样编写我们的函数来实现这一点:

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;
}

This would allow us to pass a mock forecast service into the constructor. 这将使我们能够将模拟预测服务传递给构造函数。 Dependency Injection would be better, but we don't do that yet. 依赖注入会更好,但是我们还没有这样做。

Note: We differentiate between a Unit test and an Integration test. 注意:我们区分单元测试和集成测试。 We still might write our Integration tests with Junit, but they have more of a tendency to go out and actually poke the service--this can give you advance warning of a failure. 我们仍然可以使用Junit编写集成测试,但是它们更倾向于退出并实际戳破服务-这可以给您预先警告失败。 So you might write an integration test for ForecastService that simply calls the weatherAPICallToSomeVendor method of ForecastService and ensures a non-error result (Perhaps no exceptions or doesn't return null...). 因此,您可以为ForecastService编写集成测试,该测试仅调用ForecastService的weatherAPICallToSomeVendor方法并确保无错误结果(也许没有异常,或者不返回null ...)。

I think the function needs to be rewritten as this: 我认为该功能需要这样重写:

public boolean checkForecastInCityCondition(String city, String condition){
    result = WeatherAPICallToSomeVendor(city)
    return result == condition;
}

Now you gain the advantage of exposing clients to care about arbitrary conditions and you can enhance with a new API as needed. 现在,您获得了使客户不必担心任意conditions的优势,并且可以根据需要使用新的API进行增强。 From a testing perspective you can now safely write tests like this: 从测试的角度来看,您现在可以安全地编写如下的测试:

public void testRainingInLancaster() throws Exception{
            //your code here
}

public void testSnowInRedding() throws Exception{
           //your code here
}

And you can determine which pieces need to be mocked for testing. 您可以确定需要模拟哪些零件进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM