spring 如何为 Resttemplate 交换方法编写 mockito junit

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30838512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:38:30  来源:igfitidea点击:

How to write mockito junit for Resttemplate exchange method

springjunitmockitoresttemplate

提问by Java Learing

How to write mockito junit for the method below:

如何为以下方法编写 mockito junit:

@Autowired
RestTemplate restTemplate;

ResponseEntity<?> execute(final String url, HttpMethod httpMethod,
                          HttpEntity<?> entityRequest,
                          String.class, 
                          Map<String, String> urlVariables){
    restTemplate.exchange(url, httpMethod, entityRequest, responseType, urlVariables);
}

Please help me how to write.

请帮我怎么写。

回答by Robin Schürer

@RunWith(MockitoJUnitRunner.class)
public class ToTestTest {

  @InjectMocks
  private YourClass toTest;

  @Mock
  private RestTemplate template;

  @Test
  public void test() {
    toTest.execute(Mockito.anyString(), Mockito.any(), Mockito.any(), 
                   Mockito.any(), Mockito.any());

    Mockito.verify(template, Mockito.times(1))
                    .exchange(Mockito.anyString(),
                                    Mockito.<HttpMethod> any(),
                                    Mockito.<HttpEntity<?>> any(),
                                    Mockito.<Class<?>> any(),
                                    Mockito.<String, String> anyMap());
    }
 }

回答by Marcin K?opotek

I think the most convenient and appropriate approach in this case (which is client side REST testing using RestTemplate) will be MockRestServiceServerprovided by Spring Testingframework.

我认为,在这种情况下,最方便,最合适的做法(这是客户端使用REST测试RestTemplate)将MockRestServiceServer提供弹簧试验框架。

回答by Dheeraj

I used to get such an error. I found a more reliable solution. I have mentioned the import statements too which have worked for me. The below piece of code perfectly mocks the rest template.

我曾经遇到过这样的错误。我找到了一个更可靠的解决方案。我也提到了对我有用的导入语句。下面的代码完美地模拟了其余模板。

import org.mockito.Matchers;  
import static org.mockito.Matchers.any;

    HttpHeaders headers = new Headers();
    headers.setExpires(10000L);     
    ResponseEntity<String> responseEntity = new ResponseEntity<>("dummyString", headers, HttpStatus.OK);
    when(restTemplate.exchange( Matchers.anyString(), 
            Matchers.any(HttpMethod.class),
            Matchers.<HttpEntity<?>> any(), 
            Matchers.<Class<String>> any())).thenReturn(responseEntity);

Here the 'responseEntity' value will not be null and we can use it to perfectly assert a statement.

这里的 'responseEntity' 值不会为空,我们可以用它来完美地断言一个语句。

回答by avandeursen

It depends on what you want.

这取决于你想要什么。

One way to use mocks is to make it easier to invoke the executemethod. For that, you can use mocked versions of the actual parameters, such as the HttpMethodand the HttpEntity. If the underlying exchangemethod requires certain behavior from these parameters, you may need to stub that in with mockito's when... thenReturnmethods.

使用模拟的一种方法是使调用execute方法更容易。为此,您可以使用实际参数的模拟版本,例如HttpMethodHttpEntity。如果底层exchange方法需要这些参数的某些行为,您可能需要使用 mockito 的when...thenReturn方法将其存根。

Once these mocked parameters are setup so that you can call your executemethods, you will want to check that its result is correct.

一旦设置了这些模拟参数以便您可以调用您的execute方法,您将需要检查其结果是否正确。

For checking the returned value, you can use traditional JUnit assertions.

为了检查返回值,您可以使用传统的 JUnit 断言。

Furthermore, you may want to check that certain interactionswith the mocked objects actually took place. For that you can use mockito's verifymethods to check, for example, that some HttpEntitymethod is actually invoked.

此外,您可能想要检查与模拟对象的某些交互是否实际发生。为此,您可以使用 mockito 的verify方法来检查,例如,HttpEntity确实调用了某个方法。

Technically, you could also verify that the rest template's exchangemethod is called. For that you'd need to mock the RestTemplate and inject the mock in you class under test. Then you can use mockito's verfiyto check that exchangeis called in the proper way. This typically is the sensible thing to do, especially if there are more methods to test in your class-under-test. For the present executemethod it seems a bit overkill though.

从技术上讲,您还可以验证是否exchange调用了其余模板的方法。为此,您需要模拟 RestTemplate 并将模拟注入被测类中。然后你可以使用 mockito'sverfiy来检查exchange以正确的方式调用。这通常是明智的做法,尤其是在您的待测类中有更多方法要测试时。对于目前的execute方法,它似乎有点矫枉过正。