簡體   English   中英

如何測試彈簧架操作交換

[英]How to test spring rest operation exchange

我對使用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));
}

這個模擬有什么問題?

很奇怪,當我將模擬行更改為:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM