【问题标题】:How to write mockito for below method如何为以下方法编写模拟
【发布时间】:2018-04-21 01:24:12
【问题描述】:
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);
    �
}

【问题讨论】:

    标签: mockito powermock


    【解决方案1】:

    此类代码的典型问题是您将其与其依赖项(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)....
    

    当然,如果你不能重构代码,那么你可能会被搞砸,并且需要复杂的工具(通过字节码操作可能会以某种方式实现,但老实说,这不是我想做的)。

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多