如何为此控制器编写JUnit?

时间:2019-11-29 06:14:42

标签: java junit spring-restcontroller

private static final Logger LOGGER = LoggerFactory.getLogger(InfoController.class);
    @RequestMapping(value = "/version", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, String> getVersion() throws IOException {
        final String versionKey = "Version";
        return Collections.singletonMap(versionKey, loadManifest().getProperty(versionKey));
    }
    @RequestMapping(value = "/info", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @SuppressWarnings("unchecked cast")
    public Map<String, String> getInfo() throws IOException {
        return Collections.checkedMap((Map) loadManifest(), String.class, String.class);
    }
    private Properties loadManifest() throws IOException {
        final InputStream stream = this.getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
        try {
            final Properties manifest = new Properties();
            manifest.load(stream);
            return manifest;
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e){
                    LOGGER.error(e.getMessage(),e);
                }
            }
        }
    }
}

我是JUnit的新手,也不知道如何覆盖controllers。如果能找到一个例子,那太好了,这样我就可以理解如何为其他控制器编写代码

1 个答案:

答案 0 :(得分:1)

希望MockMvc是您追求的目标 https://spring.io/guides/gs/testing-web/