在春季启动junit中模拟Resttemplate失败

时间:2018-08-13 06:29:12

标签: java spring-boot junit

我正在为称为rest api的方法编写junit测试用例,以下是我尝试过的代码:

@RunWith(MockitoJUnitRunner.class)
public class NotificationApiClientTests {

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private NotificationApiClient notificationApiClient;



    @Before
    public void setUp() throws Exception {
          MockitoAnnotations.initMocks(this);
          ReflectionTestUtils.setField(notificationApiClient, "notificationUrl", "myURL***");

    }    

@Test
    public void test_NotificationClickAPI_Call() throws JsonParseException, JsonMappingException, IOException {
        ResponseEntity<NotificationClickEvent[]> notificationClickEventList = util.getValidNotificationEvent_ResponseEntity();

        Mockito.when(restTemplate.exchange(
                Matchers.anyString(), 
                Matchers.any(HttpMethod.class),
                Matchers.<HttpEntity<?>> any(), 
                Matchers.<Class<NotificationClickEvent[]>> any()
                                  )
                                 ).thenReturn(notificationClickEventList);


        NotificationClickEvent[] notificationArray  = notificationApiClient.requestNotificationClick(Const.NotificationClick, "2018-07-31-10");
        assertTrue(notificationArray.length>0);
    }
}

在我的NotificationApiClient中,是:

@Value("${notification.base.url}")
    private String notificationUrl;

    public NotificationApiClient() {
    }

    public UserInfoEvent[] requestUserInfo(String eventType, String dateStr) {
        HttpEntity request = new HttpEntity(setHttpHeaders());
        ResponseEntity<UserInfoEvent[]> response = this.exchange(
                notificationUrl + eventType + "&dateStr=" + dateStr,
                HttpMethod.GET, request, UserInfoEvent[].class);
        UserInfoEvent[] userInfoRequest = response.getBody();
        return userInfoRequest;
    }

但是它不起作用,根据我的代码,每当调用resttemplate.exchange方法时,它应该返回notificationClickEventList,但是它调用了真正的api并将api结果返回为列表。 有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:1)

在您的代码中,您没有使用restTemplate.exchange方法,似乎您正在使用notificationApiClient's exchange方法。所以试试看。

@Spy
@InjectMocks
private NotificationApiClient notificationApiClient;


Mockito.when(notificationApiClient.exchange(
            Matchers.anyString(), 
            Matchers.any(HttpMethod.class),
            Matchers.<HttpEntity<?>> any(), 
            Matchers.<Class<NotificationClickEvent[]>> any()
                              )
                             ).thenReturn(notificationClickEventList);