使用 XUnit 在测试中运行

发布于 2025-01-11 00:11:35 字数 5219 浏览 2 评论 0原文

第一次尝试学习测试驱动设计。我有一个像这样的服务器:

public class ServerEngine
    {
        private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static List<Socket> _clientSockets = new List<Socket>();
        private static byte[] _buffer = new byte[1024];

        public ServerEngine()
        {
            SetupServer();
        }

        private void SetupServer()
        {
            Console.WriteLine("Setting up the server...");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));

            // Settingup the backlog
            _serverSocket.Listen(1);

            //Listen for connections
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private void AcceptCallback(IAsyncResult ar)
        {
            // Add the accepted socket to the list of sockets
            Socket socket = _serverSocket.EndAccept(ar);
            _clientSockets.Add(socket);
            Console.WriteLine("A client has connected");
            // listen for messages coming from the new accepted socket
            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
            // Start accepting a new connection again
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            try
            {
                var received = socket.EndReceive(ar);
                var dataBuf = new byte[received];
                Array.Copy(_buffer, dataBuf, received);

                var text = Encoding.ASCII.GetString(dataBuf);
                Console.WriteLine($"Text Received: {text}");

                var response = AddToHashSet(text);
                var data = Encoding.ASCII.GetBytes(response.ToString());
                socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
            }
            catch (SocketException)
            {
                socket.Close();
                Console.WriteLine("A client has disconnected.");
            }
        }

        private void SendCallback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            socket.EndSend(ar);
        }

        private HashSet<TidContainerModel> _tidContainerModels = new HashSet<TidContainerModel>(new TidContainerModelComparer());
        private bool AddToHashSet(string value)
        {
            var tcv = new TidContainerModel
            {
                Tid = value,
                TimeAdded = DateTime.Now,
                Type = 'R',
                Rssi = -444
            };
            return _tidContainerModels.Add(tcv);
        }
    }

我在程序主程序中调用它来设置服务器。然后我创建了一个 xUnit 测试,如下所示:

private Socket _clentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private ServerEngine serverEngine = new ServerEngine();

        [Fact]
        public void ConnectToServerTest()
        {
            // Arrange
            bool expected = true;

            // Act
            bool actual = LoopConnect();

            // Assert
            Assert.Equal(expected, actual);
        }

        private bool LoopConnect()
        {
            int attempts = 0;
            var connected = false;
            while (!_clentSocket.Connected)
            {
                try
                {
                    attempts++;
                    var ipAddress = new IPEndPoint(IPAddress.Parse("172.16.35.71"), 100);
                    _clentSocket.Connect(ipAddress);
                }
                catch (SocketException se)
                {
                    Console.Clear();
                    Console.WriteLine($"Failed connecting {se.Message}. Reconnecting attempt {attempts}");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            connected = true;
            Console.Clear();
            Console.WriteLine("Connected to the server");
            return connected;
        }

不使用测试,该程序运行良好。但是当我使用测试时,我失败并出现以下错误:

Server.Test.ServerEngineTest.ConnectToServerTest
   Source: ServerEngineTest.cs line 15
   Duration: 209 ms

  Message: 
System.IO.IOException : The handle is invalid.


  Stack Trace: 
__Error.WinIOError(Int32 errorCode, String maybeFullPath)
Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
Console.Clear()
ServerEngineTest.LoopConnect() line 51
ServerEngineTest.ConnectToServerTest() line 21

在此处输入图像描述

如果我使用控制台应用程序连接到服务器,则效果完美。我想学习如何在这个项目中使用 xUnit。

Trying to learn Test Driven Design for the first time. I have a server that goes like this:

public class ServerEngine
    {
        private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static List<Socket> _clientSockets = new List<Socket>();
        private static byte[] _buffer = new byte[1024];

        public ServerEngine()
        {
            SetupServer();
        }

        private void SetupServer()
        {
            Console.WriteLine("Setting up the server...");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));

            // Settingup the backlog
            _serverSocket.Listen(1);

            //Listen for connections
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private void AcceptCallback(IAsyncResult ar)
        {
            // Add the accepted socket to the list of sockets
            Socket socket = _serverSocket.EndAccept(ar);
            _clientSockets.Add(socket);
            Console.WriteLine("A client has connected");
            // listen for messages coming from the new accepted socket
            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
            // Start accepting a new connection again
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            try
            {
                var received = socket.EndReceive(ar);
                var dataBuf = new byte[received];
                Array.Copy(_buffer, dataBuf, received);

                var text = Encoding.ASCII.GetString(dataBuf);
                Console.WriteLine(
quot;Text Received: {text}");

                var response = AddToHashSet(text);
                var data = Encoding.ASCII.GetBytes(response.ToString());
                socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
            }
            catch (SocketException)
            {
                socket.Close();
                Console.WriteLine("A client has disconnected.");
            }
        }

        private void SendCallback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            socket.EndSend(ar);
        }

        private HashSet<TidContainerModel> _tidContainerModels = new HashSet<TidContainerModel>(new TidContainerModelComparer());
        private bool AddToHashSet(string value)
        {
            var tcv = new TidContainerModel
            {
                Tid = value,
                TimeAdded = DateTime.Now,
                Type = 'R',
                Rssi = -444
            };
            return _tidContainerModels.Add(tcv);
        }
    }

This I call in the Program Main to setup the server. Then I created an xUnit test like so:

private Socket _clentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private ServerEngine serverEngine = new ServerEngine();

        [Fact]
        public void ConnectToServerTest()
        {
            // Arrange
            bool expected = true;

            // Act
            bool actual = LoopConnect();

            // Assert
            Assert.Equal(expected, actual);
        }

        private bool LoopConnect()
        {
            int attempts = 0;
            var connected = false;
            while (!_clentSocket.Connected)
            {
                try
                {
                    attempts++;
                    var ipAddress = new IPEndPoint(IPAddress.Parse("172.16.35.71"), 100);
                    _clentSocket.Connect(ipAddress);
                }
                catch (SocketException se)
                {
                    Console.Clear();
                    Console.WriteLine(
quot;Failed connecting {se.Message}. Reconnecting attempt {attempts}");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            connected = true;
            Console.Clear();
            Console.WriteLine("Connected to the server");
            return connected;
        }

Without using the Test this program runs fine. But when I use the test, I fail with an error of:

Server.Test.ServerEngineTest.ConnectToServerTest
   Source: ServerEngineTest.cs line 15
   Duration: 209 ms

  Message: 
System.IO.IOException : The handle is invalid.


  Stack Trace: 
__Error.WinIOError(Int32 errorCode, String maybeFullPath)
Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
Console.Clear()
ServerEngineTest.LoopConnect() line 51
ServerEngineTest.ConnectToServerTest() line 21

enter image description here

If I use a console application to connect to the server, it works perfect. I want to learn how to use the xUnit with this project.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执手闯天涯 2025-01-18 00:11:35

看看你的堆栈跟踪,它告诉你问题:

  Stack Trace: 
__Error.WinIOError(Int32 errorCode, String maybeFullPath)
Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
Console.Clear()
ServerEngineTest.LoopConnect() line 51
ServerEngineTest.ConnectToServerTest() line 21

基本上,你试图清除控制台,但你的测试中没有分配控制台。这是你永远不应该做的事情,原因有两个:

  1. 你应该模拟你的 I/O 才能测试它。
  2. 你绝对不应该将这种控制台 I/O 与你的套接字服务混合在一起,无论它做什么。使用依赖注入来提取和包含控制台 I/O(或者更好的是,一个适当的日志记录接口),与启动和维护 TCP 服务器的实际工作分开。

Look at your stack trace, it's telling you the problem:

  Stack Trace: 
__Error.WinIOError(Int32 errorCode, String maybeFullPath)
Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
Console.Clear()
ServerEngineTest.LoopConnect() line 51
ServerEngineTest.ConnectToServerTest() line 21

Basically, you're trying to clear the console, but you have no console allocated in your test. Which is something you should never do for two reasons:

  1. You should be mocking your I/O to be able to test it.
  2. You should absolutely never mix this kind of console I/O with your socket service, whatever it does. Use dependency injection to extract and contain console I/O (or even better, a proper logging interface) separate from the actual work of starting and maintaining a TCP server.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文