我创建了一个简单的工厂方法,该方法以指定的模式创建HtmlUnitDriver。例如

public static HtmlUnitDriver createHtmlUnitDriver(String browserMode) {
    switch(browserMode.toLowerCase()) {
        case "chrome":
            return new HtmlUnitDriver(DesiredCapabilities.chrome());
        case "firefox":
            return new HtmlUnitDriver(DesiredCapabilities.firefox());
        case "ie":
        case "internet explorer":
            return new HtmlUnitDriver(DesiredCapabilities.internetExplorer());
        case default:
            return new HtmlUnitDriver(true);
    }
}


我想编写此方法的快速单元测试,但看不到如何判断返回的HtmlUnitDriver处于哪种“模式”。我该怎么做?

最佳答案

使用反射,您可以获得私有字段webClient

@Test
public void test() throws Exception {
    WebDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
    WebClient webClient = (WebClient) get(driver, "webClient");
    System.out.println(webClient.getBrowserVersion());
    System.out.println(webClient.getBrowserVersion().isIE());
    driver.close();
}

private static Object get(Object object, String field) throws Exception {
    Field f = object.getClass().getDeclaredField(field);
    f.setAccessible(true);
    return f.get(object);
}

10-06 15:36