【问题标题】:How to test spring rest operation exchange如何测试弹簧休息操作交流
【发布时间】:2015-08-07 12:29:08
【问题描述】:

我在测试使用 RestOperation 交换方法的方法时遇到问题。当我尝试模拟响应时出现错误:

ResponseEntity cannot be returned by toString()
toString() should return String
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 

下面是我要测试的课程

@Component
public class AuthGateway {

@Autowired
AuthorizedHttpEntityFactory authorizedHttpEntityFactory;

@Autowired
RestOperations restOperations;

@Value("${authServer.host}:${authServer.port}/${authServer.validateToken.path}")
private String authPath;
@Value("${authServer.host}:${authServer.port}/basic/check")
private String basicAuthPath;
@Value("${authServer.tokenName}")
private String tokenName;
@Value("${authServer.host}:${authServer.port}/user")
private String userProfileUrl;
@Value("${authServer.host}:${authServer.port}/homeowner")
private String homeownerUrl;

public UnpackedToken authenticate(String token) throws ResourceAccessException, AuthException {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add(tokenName, token);

    HttpEntity httpEntity = authorizedHttpEntityFactory.getAuthorizedHttpEntity(formData);

    Map map = null;
    try {
        ResponseEntity<Map> entity = restOperations.exchange(authPath, HttpMethod.POST,
                httpEntity, Map.class);
        map = entity.getBody();
    } catch (RestClientException e) {
        processError(e);
    }
    @SuppressWarnings("unchecked")
    Map<String, Object> result = map;

    return new UnpackedToken(result);
}

和测试类

@RunWith(MockitoJUnitRunner.class)
public class AuthGatewayTest {

private ResponseEntity<Map> entity;

@Mock
private RestOperations restOperations;

@Mock
private LinkedMultiValueMap linkedMultiValueMap;

@Mock
private AuthorizedHttpEntityFactory authorizedHttpEntityFactory;

@Autowired
@InjectMocks
private AuthGateway authGateway;

private String token;

private Integer userId = 1;
private String role = "ROLE_PRO";

private UnpackedToken unpackedToken;
private Map<String, Object> map;

private RestClientException restClientException;
private AuthException authException;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    restClientException = new RestClientException("Test exception");
    authException = new AuthException("Test exception");

    token = "token-token";

    map = new HashMap<>();
    map.put("UserId", userId);
    map.put("authorities", Collections.singletonList(role));

    entity = new ResponseEntity<>(map, HttpStatus.OK);

    unpackedToken = new UnpackedToken(map);

}

@Test
public void testAuthenticateSuccessfully() throws Exception {

    HttpEntity httpEntity = new HttpEntity("body");

    Mockito.when(authorizedHttpEntityFactory.getAuthorizedHttpEntity(any(Map.class))).thenReturn(httpEntity);
    Mockito.when(restOperations.exchange(
            Mockito.anyString(), Mockito.<HttpMethod>any(), Mockito.<HttpEntity<?>>any(), Mockito.<Class<Map>>any())).
            thenReturn(entity);

    Mockito.doNothing().when(linkedMultiValueMap).add(any(), any());

    assertEquals(this.unpackedToken, authGateway.authenticate(token));
}

这个模拟有什么问题?

【问题讨论】:

    标签: spring rest spring-boot


    【解决方案1】:

    很奇怪,当我将模拟行更改为:

    Mockito.when(restOperations.exchange(
                Mockito.anyString(), Mockito.<HttpMethod>any(), Mockito.<HttpEntity<?>>any(), Mockito.<Class<Map>>any())).
                thenReturn(new ResponseEntity<>(map, HttpStatus.OK));
    

    然后它开始正常工作......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多