單元測試——Mock RestTemplate


service代碼如下:

public class TestServiceImpl implements ITestService {
    @Autowired
    RestTemplate restTemplate;

    @Override
    public String getUserName(String sid) {
        String userName = "";
        //拼接url
        String url = "XXX";
        JSONObject result = restTemplate.getForObject(url, JSONObject.class);
        log.info("調用平台接口:{} ,返回參數為:{}", url, result.toJSONString());
        //獲取接口返回信息
        if ("0000".equals(result.getString("code"))) {
            if (result.getJSONObject("data") != null) {
                user = result.getJSONObject("data").getString("user");
            }
        } else {
            log.error("調用平台接口返回錯誤");
        }
        return userName;
    }
}

下面,我們編寫單元測試,代碼如下:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootMain.class)
public class TestServiceImplTest extends BaseTest {

    @Mock
    private RestTemplate restTemplate;
    @InjectMocks
    TestServiceImpl testService;

    /**
     * 注入一個web應用環境(容器)
     */
    @Resource
    WebApplicationContext webApplicationContext;
    // mvc 環境對象
    public MockMvc mockMvc;

    @Before
    public void init()throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testGetUserName() {
        String res = "{\"code\":\"0000\",\"data\":{\"name\":\"test\"},\"message\":\"成功\"}";
        Mockito.when(restTemplate.getForObject(Mockito.anyString(), Mockito.any())).thenReturn(JSONObject.parseObject(res));
        testService.getUserName("test");
    }

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM