Вот мой тестовый пример
@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpClient.class,PostMethod.class})
public class MessageProcessorTest {
//@Spy
@InjectMocks
MessageServiceImpl messageServiceImpl;
//@Mock
//HttpClient httpClient;
//@Mock
//PostMethod postMethod;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(PostMethod.class);
PowerMockito.mockStatic(HttpClient.class);
//this.httpClient=mock(HttpClient.class);
}
@Test
public void sendPayloadToItemMigrationServiceTest() throws HttpException, IOException, ParseException {
ReflectionTestUtils.setField(messageServiceImpl, "baseServiceUrl",
"http://localhost:8080/");
ReflectionTestUtils.setField(messageServiceImpl, "apiItemServiceUrl",
"item");
ReflectionTestUtils.setField(messageServiceImpl,
"apiItemGroupServiceUrl", "itemGroup");
File file = new File(getClass().getClassLoader()
.getResource("validItem.json").getFile());
JSONParser jsonParser = new JSONParser();
// HttpClient httpClient = Mockito.mock(HttpClient.class);
HttpClient httpClient = PowerMockito.mock(HttpClient.class);
//PostMethod postMethod = PowerMockito.mock(PostMethod.class);
Object obj = jsonParser.parse(new FileReader(file));
// when(httpClient.executeMethod(Matchers.any(PostMethod.class))).thenReturn(200);
when(httpClient.executeMethod(PowerMockito.mock(PostMethod.class)))
.thenReturn(200);
messageServiceImpl.getItemMigtn(obj.toString(),
"item");
verify(httpClient, times(1)).executeMethod(
Mockito.any(PostMethod.class));
}
Здесь, когда мы выполняем httpClient.executemethod (postMethod), он не возвращает 200.
И мой фактический класс
@Retryable(
value={Exception.class},
maxAttempts=3,
backoff=@Backoff(delay=5000)
)
public String getItemMigtn(String data,String line) throws Exception {
// Read from request
String jsonReceive = null;
String type = "item";
try{
StringRequestEntity requestEntity = null;
StringBuffer eventResponse = new StringBuffer();
HttpClient httpclient = new HttpClient();
InputStream inputStream = null;
int statusCode;
BufferedReader br = null;
PostMethod postMethod=new PostMethod();
logger.info("RequestJson" + data);
requestEntity = new StringRequestEntity(data, MEDIA_TYPE, FORMAT);
if (type.equalsIgnoreCase("item")) {
postMethod = new PostMethod( baseServiceUrl + apiItemServiceUrl);
} else if (type.equalsIgnoreCase("itemGroup")) {
postMethod = new PostMethod(baseServiceUrl + apiItemGroupServiceUrl);
}
postMethod.setRequestEntity(requestEntity);
statusCode = httpclient.executeMethod(postMethod);
logger.info("Status code from service call" + statusCode);
if(statusCode!=200) {
throw new Exception("Error in service call");
}
inputStream = postMethod.getResponseBodyAsStream();
if (null != inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream, FORMAT));
for (line = br.readLine(); line != null; line = br.readLine()) {
eventResponse = eventResponse.append(line);
}
}
jsonReceive = eventResponse.toString();
logger.info("JsonReceive" + jsonReceive);
}
catch(Exception e){
logger.info("Exception occurs "+e);
throw new Exception("Exception occurs "+e);
}
return jsonReceive;
}
Пока я запускаю тестовый пример, я получил что-то вроде 404 и выбросил исключение, которое я указал в коде, например «Ошибка при вызове службы», и макет не работает для HttpClient, где я допустил ошибку ?? Может ли кто-нибудь помочь мне получить код состояния как 200.