小编c23*_*878的帖子

如何在Java Spring中模拟RestTemplate?

public class ServiceTest {
    @Mock
    RestTemplate restTemplate = new RestTemplate();
    @InjectMocks
    Service service = new Service();
    ResponseEntity responseEntity = mock(ResponseEntity.class);

    @Test
    public void test() throws Exception {
        Mockito.when(restTemplate.getForEntity(
                Mockito.anyString(),
                Matchers.any(Class.class)
                ))
                .thenReturn(responseEntity);
        boolean res = service.isEnabled("something");
        Assert.assertEquals(res, false);
    }
Run Code Online (Sandbox Code Playgroud)

我试图测试一个包含restclient的服务的简单测试.它看起来我没有RestTemplate成功模拟.它看起来像代码获得真实数据而不是模拟数据.任何人都可以帮助我.

服务本身看起来像这样:

public class Service{
    public boolean isEnabled(String xxx) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity("someurl",String.class);
        if(...)return true;
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

java unit-testing spring-mvc mockito

17
推荐指数
2
解决办法
5万
查看次数

如何让Java rest api调用立即返回不等?

@RequestMapping(value = "/endpoint", method = RequestMethod.POST)
    public ResponseEntity<?> endpoint(@RequestBody final ObjectNode data, final HttpServletRequest request) {
        somefunction();
        return new ResponseEntity<>(HttpStatus.OK);
    }


public somefunction() {
 .....
 }
Run Code Online (Sandbox Code Playgroud)

在Java spring controller中,我有一个端点.调用此端点时,我希望它直接返回,而不是等待somefunction()完成.任何人都可以教我如何处理这个问题?

java spring asynchronous

5
推荐指数
2
解决办法
3588
查看次数

标签 统计

java ×2

asynchronous ×1

mockito ×1

spring ×1

spring-mvc ×1

unit-testing ×1