如何为以下方法编写mockito

时间:2018-04-21 01:24:13

标签: mockito powermock

public List<Locatins> fetchLocations() {
        BasicAuthRestTemplate restTemplate = new BasicAuthRestTemplate(config.getUsername(),config.getPassword());
        String locationsOData =  restTemplate.getForObject(config.getOdataUrl()+config.getLocations(), String.class);
        String results = StringUtility.changeUIFieldCase(locations);
        return map.Locations(results);
    }




@Test
    public void fetchLocationsTest() throws Exception {�

        List<Locations> li = new ArrayList<>();
        String locationData = "noting";
        when(config.getUsername()).thenReturn(“test1”);
        when(config.getPassword()).thenReturn("test12”);
        when(config.getTdsOdataUrl()).thenReturn("https://localhost:8080");
        when(config.getLocations()).thenReturn("/locations");
        PowerMockito.mockStatic(BasicAuthRestTemplate.class);
        PowerMockito.whenNew(BasicAuthRestTemplate.class).withArguments(config.getUsername(), config.getPassword()).thenReturn(restTemplate);
        PowerMockito.when(restTemplate.getForObject("https://localhost:8080/locations",String.class)).thenReturn(locationData);
    �
}

1 个答案:

答案 0 :(得分:0)

像这样的代码的典型问题是你强烈地将它与它的依赖关系(BasicAuthRestTemplate)耦合在一起:

BasicAuthRestTemplate restTemplate = new BasicAuthRestTemplate(config.getUsername(),config.getPassword());

此代码将始终使用此restTemplate,而不会使用其他任何内容。你非常严格地绑定两个软件。这意味着你a)不能简单地在其他情况下使用你的代码(例如,如果你得到另一个不使用基本身份验证的REST服务,你必须更改这个代码)和b)它可能很难测试,因为字面上这个代码唯一能做的就是通过基本身份验证连接到某些东西。

Powermock和类似工具几乎总是指出代码味道。如果您需要非常复杂和复杂的工具来测试代码,那么代码可能很糟糕。

因此,如果可能的话,我建议通过注入RestTemplate来重构代码:

public List<Locatins> fetchLocations(RestTemplate restTemplate) {        
        String locationsOData =  restTemplate.getForObject(config.getOdataUrl()+config.getLocations(), String.class);
        String results = StringUtility.changeUIFieldCase(locations);
        return map.Locations(results);
    }

这将是最简单的方法,但当然你也可以通过Spring(@Autowired等)将它注入到类中。重要的一点是,通过将依赖项注入代码而不是“硬连接”它,将依赖项与代码分开。

使用上面的代码,您可以更简单地测试它......

RestTemplate template = mock(BasicAuthRestTemplate.class);
Mockito.when(template...).thenReturn(...);
List<Locations> result = fetchLocations(template);
assertThat(result)....

当然,如果你不能重构代码,那么你可能会搞砸了一些并且需要复杂的工具(它可能以某种方式使用字节码操作,但说实话,我不想做任何事情)。

相关问题