如何使用mockito模拟restemplate的最后一个新示例

ztyzrc3y  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(375)
Component
public class MyService {
  private final ObjectMapper objectMapper = new ObjectMapper();
  private final RestTemplate restTemplate = new RestTemplate();

  public void myMethod(){

    ------- codes to test above it------ 

     HttpEntity<String> httpEntity = new HttpEntity<>(objectMapper
          .writeValueAsString(message), httpHeaders);
      String response = restTemplate
          .postForObject(getUrl(), httpEntity, String.class);

  }

}

我试过@spy,但没用

@InjectMocks
  private MyService myService;

  @Spy
  private RestTemplate restTemplate;

 when(restTemplate.postForObject(
    getUrl(),
    httpEntity,
    String.class
)).thenReturn(getResponse());
chhkpiq4

chhkpiq41#

如果你想监视:

@Test
void test(){
    MyService myService = Mockito.spy(MyService.class);
    myService.myMethod();
}

这样,就得到了restemplate的示例。
我个人更喜欢接收restemplate作为一个依赖项,这使得它很容易被模仿。
例如:

private final RestTemplate restTemplate;

public MyService(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
}

在你的测试中

//@RunWith(MockitoJUnitRunner.class) //junit4
@ExtendWith(MockitoExtension.class) //junit 5
public class MyServiceTest {

@Mock
private RestTemplate restTemplate;

@InjectMocks
private MyService myService;

@Test
void test(){
    when(restTemplate.postForObject(
            getUrl(),
            httpEntity,
            String.class
    )).thenReturn(getResponse());
    //do whatever you like
   }

}
xghobddn

xghobddn2#

springboot测试提供了一种通过mockbean和spybean注解模拟bean的好方法。
尝试使用 @SpyBean 而不是 @Spy 以及 @MockBean 而不是 @Mock .

@MockBean
private RestTemplate restTemplate

在这种情况下没有 @InjectMocks 必修的。

相关问题