我知道这个问题已经在stackoverflow多次被问到,但是在某种程度上,仍然有一些麻烦找出一个解决方案.以下示例我认为是静态方法的好例子
public class ConnectionFactory
{
public static Connection createConnection(ConnectionType connectionType, String ipAddr, Integer port)
{
//Some error checking
switch(connectionType)
{
case TCP:
return createTcpConnection(ipAddr, port);
case UDP:
return createUdpConnection(ipAddr, port);
case RTP:
return createRtpConnection(ipAddr, port);
case SCTP:
return createRtpConnection(ipAddr, port);
default:
break;
}
}
// TcpConnection, RtpConnection, SctpConnection and UdpConnection implement interface Connection
public Connection createTcpConnection()
{
Connection connection = new TcpConnection();
.....
.....
return connection;
}
public Connection createUdpConnection()
{
Connection connection = new UdpConnection();
.....
.....
return connection;
}
....
....
}
假设我有一个CommunicationService,如下所示
public class CommunicationService
{
public void initConnectionPool(ConnectionType connectionType)
{
for(int i = 0; i < MAX_CONNECTIONS; i++)
connectionList.add(ConnectionFactory.createConnection(connectionType, "domain.com", 40203));
//Some more code here to do further processing
......
......
}
//Some more methods
}
像这样,不同的通信服务可以创建和维护多种类型的连接.
我想测试initConnectionPool方法,在单元测试环境中,套接字创建一定会失败.
我可以将ConnectionFactory更改为一个具体的类,并将其嘲笑.但是这种情况不是用静态方法创建一个类的好的情况吗?我不想在ConnectionFactory中维护任何状态.那么,如果使用静态方法在适当的地方可能会导致测试问题,我们什么时候使用静态方法?还是不适合在这里使用静态方法?
编辑:解决方案我去了
public class CommunicationService
{
public void initConnectionPool(ConnectionType connectionType)
{
for(int i = 0; i < MAX_CONNECTIONS; i++)
connectionList.add(connectToHost(connectionType));
//Some more code here to do further processing
......
......
}
public Connection connectToHost(ConnectionType connectionType)
{
ConnectionFactory.createConnection(connectionType, "domain.com", 40203)
}
//Some more methods
}
在测试中overconnectedToHost并返回了一个模拟.