我知道如何通过运行程序来对其进行实验测试,但理想情况下,我想在编写时测试我编写的每个函数。通常,在我编写一大堆函数之前,我无法测试我的函数,这使得很难找出问题所在。
Posix 是否有某种方法来测试套接字的选项、标志、设置等,以便我可以为这样的函数编写测试用例?
测试此类功能的最佳方法是什么?
/**
* Creates a listening socket, sets it up with setsockopt, bind, and listen.
* @param port the port of the listening socket.
* @return the file descriptor of the listening socket.
*/
int SetUpListeningSocket(int port)
{
//Variables:
struct sockaddr_in server;
int s;
// setup socket address structure
memset(&server, 0, sizeof (server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
// create socket
s = socket(PF_INET, SOCK_STREAM, 0);
if (!s)
{
perror("socket");
exit(-1);
}
// set socket to immediately reuse port when the application closes
int opt = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) < 0)
{
perror("setsockopt");
exit(-1);
}
// call bind to associate the socket with our local address and
// port
if (bind(s, (const struct sockaddr *) &server, sizeof (server)) < 0)
{
perror("bind");
exit(-1);
}
// convert the socket to listen for incoming connections
if (listen(s, SOMAXCONN) < 0)
{
perror("listen");
exit(-1);
}
return s;
}