问题描述
我正在为下面的ENUm类编写JUNIT测试用例。我下面的类只会给我运行我的代码的当前机器的主机名。当我在写JUNIT测试时,我如何嘲笑下面的类,所以我想改变 getHostName()
方法,以便每当我调用 getDatacenter()
,它可以返回我通过嘲笑它传递的任何主机名。我不想让它作为一个参数化。
I am working on writing JUNIT test case for my below ENUm class. My below class will only give me the hostname for the current machine where I am running my code. While I am writing JUNIT test, how can I mock the below class, so that I can change getHostName()
method whenever I want to so that whenever I am calling getDatacenter()
, it can return me whatever hostname I am passing by mocking it. I don't want to make it as a parametrized.
我只是想在一些更改主机名的同时测试某些情况,而嘲笑它。
I just want to test certain cases while changing the hostname while mocking it.
public enum DatacenterEnum {
DEV, DC1, DC2, DC3;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
private static final String getHostName() {
try {
return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
} catch (UnknownHostException e) {
s_logger.logError("error = ", e);
}
return null;
}
public static String getDatacenter() {
return getHostName();
}
}
推荐答案
可能是老学校,但我真的会重新测试代码,而不是使用classloader hacks。例如:
I may be old school, but I'd really refactor the code under test rather than using classloader hacks. Something like:
public enum DatacenterEnum {
DEV, DC1, DC2, DC3;
static String hostName = InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
public static String getHostName() {
return hostName;
}
}
在测试代码中,在运行测试之前:
and in your test code, prior to running the test:
DataCenterEnum.hostName = "foo";
这篇关于如何模拟ENUM类中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!