如何使用spring boot和mockbeam测试Rest API和模拟URL

时间:2017-07-17 05:33:22

标签: java rest spring-boot mocking integration-testing

我有一个Rest API

班级代码是:

@SpringBootTest 
@RunWith(SpringRunner.class)

public class FetchCoreVersionsListIT {

@MockBean
private RestTemplateBuilder restTemplateBuilder;

@MockBean
private RestTemplate restTemplate;
private VersionsService versionsService;

@Autowired
private FetchCoreVersionsList fetchCoreVersionsList;


private VersionList versionList;

private ArtifactoryFolderInfoChild version;

@Before
public void setUp() throws Exception {
    this.version = new ArtifactoryFolderInfoChild();
    this.version.setUri("2.1.0");
    this.version.setFolder(true);
    when(restTemplateBuilder.build()).thenReturn(restTemplate);

}

@Test
public void testCoreVersionsJsonHandle() throws Exception{
    when(restTemplate.getForObject("https://openmrs.jfrog.io/openmrs/api/storage/public/org/openmrs/api/openmrs-api/",
            String.class))
            .thenReturn(getFileAsString("core-versions.json"));
   ("2.1.0"));*/

}

这是core-versions.json。这只是从this Rest API收到的数据。

基本上我试图运行测试,我有一个春季计划,将解析从该网址收到的json。现在,在测试时间表时,我想返回相同的数据,但没有连接到互联网,因此想要返回core-versions.json的内容。遗憾的是我得到以下错误:

java.lang.IllegalStateException: File downloaded from  could not be parsed

我的日程安排课程是:

@Component
public class FetchCoreVersionsList {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String[] STRINGS_TO_EXCLUDE = {"alpha", "beta", "RC", "SNAPSHOT"};

    @Value("${core_version_list.url}")
    private String url;

    //@Value("${core_version_list.strategy}")
    //private FetchCoreVersionsList.Strategy strategy = FetchCoreVersionsList.Strategy.FETCH;

    private RestTemplateBuilder restTemplateBuilder;

    private ObjectMapper mapper;

    private VersionsService versionsService;

    @Autowired
    public FetchCoreVersionsList(RestTemplateBuilder restTemplateBuilder,
                                 ObjectMapper mapper,
                                 VersionsService versionsService) {
        this.restTemplateBuilder = restTemplateBuilder;
        this.mapper = mapper;
        this.versionsService = versionsService;
    }

    @Scheduled(
            initialDelayString = "${scheduler.fetch_core_versions_list.initial_delay}",
            fixedDelayString = "${scheduler.fetch_core_versions_list.period}")
    public void fetchCoreVersionsList() throws Exception {
        logger.info("Fetching list of OpenMRS-Core versions");
       // FetchCoreVersionsList.Strategy strategy = FetchCoreVersionsList.Strategy.FETCH;
        String json;
       /* if (strategy == Strategy.LOCAL) {
            logger.debug("LOCAL strategy");
            json = StreamUtils.copyToString(getClass().getClassLoader().getResourceAsStream("openmrs-core-versions.json"),
                    Charset.defaultCharset());
        } else {*/

            json = restTemplateBuilder.build().getForObject(url, String.class);
            logger.info("FETCH strategy: " + json);

        ArtifactoryFolderInfo versionlist;
        try { logger.info("FETCH strategy: " + json);
            logger.debug("papa strategy: " + url);
            versionlist = mapper.readValue(json, ArtifactoryFolderInfo.class);
        } catch (Exception ex) {
            throw new IllegalStateException("File downloaded from " + url + " could not be parsed", ex);
        }
        if (logger.isInfoEnabled()) {
            logger.info("There are " + versionlist.getChildren().size() + " openmrs-core versions");
        }
        if (versionlist.size() > 0) {
            List<String> versions = new ArrayList<>();
            List<ArtifactoryFolderInfoChild> allversions = versionlist.getChildren();
            for (ArtifactoryFolderInfoChild candidateVersion : allversions) {
                if (candidateVersion.getFolder() && !stringContainsItemFromList(candidateVersion.getUri(), STRINGS_TO_EXCLUDE)) {
                    versions.add(candidateVersion.getUri().replaceAll("/", ""));
                }
            }
            versionsService.setVersions(versions);
        } else {
            logger.warn("File downloaded from " + url + " does not list any Core Versions to index. Keeping our current list");
        }
    }

    private static boolean stringContainsItemFromList(String inputStr, String[] items) {
        return Arrays.stream(items).parallel().anyMatch(inputStr::contains);
    }

    public enum Strategy {
        FETCH, LOCAL
    }
}

如果这是一个愚蠢的错误,请耐心等待,因为我对测试完全不熟悉。

0 个答案:

没有答案