我是测试自动化的新手(Mockito
,JUnit
),我不知道如何测试以下类。方法中有最终的类,空白和异常,并且非常难。
private final static String SERVER="http://testserver:9086";
private void checkServerr() throws myException {
try {
URL hp = new URL(SERVER);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
} catch (Exception e) {
throw new myException("Server " + SERVER + " not available");
}
}
答案 0 :(得分:1)
为了使这个可测试,首先你需要稍微折射一下:
private void checkServerr() throws myException {
return checkServer(SERVER);
}
protected void checkServer(String server) throws my exception {
try {
URL hp = new URL(server);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
} catch (Exception e) {
throw new myException("Server " + server + " not available");
}
}
现在,您可以测试将服务器地址作为字符串的新受保护方法。
我在这里只看到两件事要测试:
答案 1 :(得分:0)
在阅读了Janos的回答之后,我想到了以下内容。
在服务类MyService.java
中集成URLConnection的创建:
public class MyService {
private static final String MYSERVER = "http://testserver:9086";
public URLConnection createConnection(Properties properties) throws MalformedURLException, IOException {
return new URL(MYSERVER).openConnection();
}
}
然后是myinitial class myClass.java
:
public class myClass {
private URLConnection serverConnection;
private void checkServer() throws myException {
MyService service = new MyService();
try {
serverConnection = service.createConnection();
serverConnection.connect();
} catch (Exception e) {
throw new myException("Server " + SERVER + " not available");
}
}
}
测试将是:
@Mock
private URLConnection serverConnection;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCheckInfrastructure() throws myException,
IOException {
Mockito.doNothing().when(serverConnection).connect();
myClass.checkServer();
}
@Test(expected = myException.class)
public void testCheckServerException() throws myException, IOException {
Mockito.doThrow(myException.class).when(serverConnection).connect();
myClass.checkServer();
}