Проблема на Mock New Object с помощью PowerMockitoJAVA

Программисты JAVA общаются здесь
Anonymous
Проблема на Mock New Object с помощью PowerMockito

Сообщение Anonymous »

По сути, у меня есть класс Twsconnector, с 1 методом, который обеспечивает соединение с помощью вызова REST для клиента, который планирует задание. < /p>
Это класс: < /p>
@Service
public class TwsConnector {

@Autowired
private PropertiesConfig propertiesConfig;

private static final Logger logger = LoggerFactory.getLogger(TwsConnector.class);

public void addSchedulingOnTws(TwsRequest record) throws ApiException {

ApiClient client = new ApiClient();
client.setBasePath(propertiesConfig.getTwsApiUrl());
client.setUsername(propertiesConfig.getTwsApiUsername());
client.setPassword(propertiesConfig.getTwsApiPassword());

PlanApi plan = new PlanApi(client);

OffsetDateTime offsetDateTime = OffsetDateTime.of(
record.getTsOperation().toLocalDateTime().getYear(),
record.getTsOperation().toLocalDateTime().getMonthValue(),
record.getTsOperation().toLocalDateTime().getDayOfMonth(),
record.getTsOperation().toLocalDateTime().getHour(),
record.getTsOperation().toLocalDateTime().getMinute(),
record.getTsOperation().toLocalDateTime().getSecond(),
0,
ZoneOffset.UTC
);

SubmitZOSJobStreamInfo submitJobStreamInfo = new SubmitZOSJobStreamInfo();
submitJobStreamInfo.setName(record.getJobStreamName());
submitJobStreamInfo.setStartTime(offsetDateTime);
submitJobStreamInfo.setPriority(5);
submitJobStreamInfo.setHoldAll(false);

QueryFilterPlan body = new QueryFilterPlan();
FiltersPlan filters = new FiltersPlan();
JobStreamInPlanFilter jobStreamInPlanFilter = new JobStreamInPlanFilter();
jobStreamInPlanFilter.setJobStreamName(record.getJobStreamName());
filters.setJobStreamInPlanFilter(jobStreamInPlanFilter);
body.setFilters(filters);
logger.info("Searching on TWS JobStream:");
logger.info("Searching Param [Name]: [" + record.getJobStreamName() + "]");
logger.info("Searching Param [Timestamp]: [" + offsetDateTime.toString() + "]");
logger.info("Searching Param [Engine]: [" + propertiesConfig.getTwsApiEngine() + "]");
List jobStreamInPlanList = plan.queryJobStreamInPlan(propertiesConfig.getTwsApiEngine(), "current", body, null, null);
System.out.println("SIZE: "+jobStreamInPlanList.size());
String jobStreamId="";
for(JobStreamInPlan jobStream : jobStreamInPlanList) {
if(jobStream.getTimeRestriction().getStartTime().equals(offsetDateTime)) {
jobStreamId = jobStream.getId();
}
}

if(jobStreamId!="") {
logger.info("JobStream on TWS founded!");
logger.info("Set JobStream with [Name]:[" + record.getJobStreamName() + "] and [Timestamp]: [" + offsetDateTime.toString() + "] to WAITING on TWS!");
plan.setToWaitJobStreamInstance(propertiesConfig.getTwsApiEngine(), jobStreamId, "current", null);
} else {
logger.info("JobStream on TWS not founded!");
logger.info("Scheduling JobStream with [Name]:[" + record.getJobStreamName() +"] and [Timestamp]: [" + offsetDateTime.toString() + "] on TWS!");
plan.addJobStreamInstance(propertiesConfig.getTwsApiEngine(), "current", submitJobStreamInfo, null);
}

}

}
< /code>
, а затем мне нужно покрыть тест на JUNIT Метод добавляет, что записи TWSRequest). Я написал этот тест: < /p>
@ExtendWith(MockitoExtension.class)
@RunWith(PowerMockRunner.class)
@PrepareForTest({TwsConnector.class, ApiClient.class, PlanApi.class})
public class TwsConnectorTest {

@Mock
private PropertiesConfig propertiesConfig;

@Mock
private ApiClient mockedApiClient;

@Mock
private PlanApi mockedPlanApi;

@InjectMocks
private TwsConnector twsConnector;

@BeforeEach
public void setUp() throws Exception {
PowerMockito.when(propertiesConfig.getTwsApiUrl()).thenReturn("https://example.com/");
PowerMockito.when(propertiesConfig.getTwsApiUsername()).thenReturn("MockedUser");
PowerMockito.when(propertiesConfig.getTwsApiPassword()).thenReturn("MockedPassword");
PowerMockito.when(propertiesConfig.getTwsApiEngine()).thenReturn("MockedEngine");
}

@Test
public void testAddSchedulingOnTws() throws Exception {

Timestamp tms = new Timestamp(System.currentTimeMillis());
OffsetDateTime offsetDateTime = OffsetDateTime.of(
tms.toLocalDateTime().getYear(),
tms.toLocalDateTime().getMonthValue(),
tms.toLocalDateTime().getDayOfMonth(),
tms.toLocalDateTime().getHour(),
tms.toLocalDateTime().getMinute(),
tms.toLocalDateTime().getSecond(),
0,
ZoneOffset.UTC
);

List mockedJobStreamInPlanList = new ArrayList();
JobStreamInPlan mockedjobStreamInPlan = new JobStreamInPlan();
JobStreamInPlanKey mockedKey = new JobStreamInPlanKey();
mockedKey.setName("mocked");
mockedjobStreamInPlan.setKey(mockedKey);
TimeRestrictionsInPlan timeRestrictionsInPlan = new TimeRestrictionsInPlan();
timeRestrictionsInPlan.setStartTime(offsetDateTime);
mockedjobStreamInPlan.setTimeRestriction(timeRestrictionsInPlan);
mockedJobStreamInPlanList.add(mockedjobStreamInPlan);

PowerMockito.whenNew(PlanApi.class).withArguments(Mockito.any(ApiClient.class)).thenReturn(mockedPlanApi);
PowerMockito.when(mockedPlanApi.queryJobStreamInPlan(anyString(), anyString(), any(), any(), any())).thenReturn(mockedJobStreamInPlanList);

TwsRequest twsRequest = new TwsRequest();
twsRequest.setJobStreamName("mocked");
twsRequest.setTsOperation(tms);

twsConnector.addSchedulingOnTws(twsRequest);

}

}
< /code>
Тест, очевидно, еще не завершен, но я хотел бы начать тестирование первой части кода.PowerMockito.whenNew(PlanApi.class).withArguments(Mockito.any(ApiClient.class)).thenReturn(mockedPlanApi);
PowerMockito.when(mockedPlanApi.queryJobStreamInPlan(anyString(), anyString(), any(), any(), any())).thenReturn(mockedJobStreamInPlanList);
< /code>
Во время выполнения тестирования новый объект типа Apiclient создается создание и в ответ новый объект Planapi. Поэтому, когда называется метод «QueryJobStreamInplan», набор макет не получена, и предпринимается реальная попытка подключения, которая, очевидно, терпит неудачу.>

Подробнее здесь: https://stackoverflow.com/questions/764 ... wermockito

Вернуться в «JAVA»