简体   繁体   中英

Mockito any(Class.class)

I'm stumped how to mock a method that accepts a Class as an argument. like for example.

restTemplate.exchange(someUrl, HttpMethod.GET, httpEntity, SomeEntityModel.class, code)

Any combinations of any(Class.class) or any(Class<SomeEntityModel>.class) or what have you just generates some new error messages.

Have never stumbled to such use case.

Any suggestsions how to mock this method so that it would work for any Class.class.

Any suggestions hot to mock this method so that it would work for specific Class<T>.class

You can use an ArgumentCaptor :

final ArgumentCaptor<Class<SomeEntityModel>> classArgumentCaptor = ArgumentCaptor.forClass(Class.class);
final ResponseEntity<SomeEntityModel> responseEntity = mock(ResponseEntity.class);

Mockito.when(restTemplate.exchange(eq(someUrl), eq(HttpMethod.GET), eq(httpEntity), classArgumentCaptor.capture(), eq(code))
    .thenReturn(responseEntity);

// TODO execute the code which will invoke the mock

Assertions.assertThat(classArgumentCaptor.getValue()).isEqualTo(SomeEntityModel.class);

The idea is that your mocked method will be invoked and you can check if the parameter was the expected one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM