单元测试——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

posted @ 2021-04-09 16:29  super_龙  阅读(1167)  评论(0编辑  收藏  举报