需要帮助为服务层方法编写 JUnit 测试用例,该方法有 rest 调用

问题描述 投票:0回答:0

My service layer code:

public String fileUpload(Multipart file, String payload, HttpHeaders headers) throws Exception{
MultiValueMap\<String,Object\> map = new LinkedMultiValueMap\<\>();
map.add("file",file.getResource());
map.add("payload",payload);
RestTemplate rest = new RestTemplate();
ResponseEntity\<String\> rEntity = null;
HttpEntity\<MultiValueMap\<String,Object\>\> request = new HttpEntity\<\>(map,headers);
try{
rEntity = rest.exchange("https//test.dummy.com/v1/fileupload",HttpMethod.POST,request,String.Class);
}catch(Exception e){
e.printStackTrace();
}
String result = rEntity.getBody();
return result;
}
I tried to mock the RestTemplate class but its failing. Its calling to the service layer actual 
rest.exchage()。但由于身份验证问题,它在那里失败了。
 
需要你的帮助....`

public class UploadTest {
@Mock
private RestTemplate rest;
@Autowared
你的文字
 
private UploadServiceImpl impl;
 
@Autowared
 
private UploadServiceUtil implUtil;
 
@SpringBootTest
 
public class UploadFileTest{
 
@Test
 
public void testUploadFileESB()异常{
 
MockMultipartFile mockFile = new MockMultipartFile("file", "test.pdf",
MediaType.TEXT_PLAIN_VALUE, "Hello world".getBytes());
String metadata = "{"object":"Doc","properties":     \[{"name":"src","value":"test"}," +
"{"name":"colname","value":"colval"}"\]};
String fileId = "345d";
HttpHeaders headers = implutil.getHeaders(metadata);
Mockito.when(impl.uploadSingleESBFile(mockFile, metadata, headers)).thenReturn(fileId);
}
}

junit mockito spring-test junit-jupiter spring-resttemplate
© www.soinside.com 2019 - 2024. All rights reserved.