How to test, write unit test for UDP sender? Code:

byte[] number = Encoding.ASCII.GetBytes(numb.ToString()); UdpClient udpclient = new UdpClient(); IPAddress multicastaddress = IPAddress.Parse(_instance.configuration.ip); udpclient.JoinMulticastGroup(multicastaddress); IPEndPoint remoteep = new IPEndPoint(multicastaddress, _instance.configuration.port); udpclient.Send(number, number.Length, remoteep); udpclient.Close(); 

    1 answer 1

    Strictly speaking, unit tests for such code do not write. Because unit tests, by definition, should not depend on the external environment (in this case, the network). How, then, to do?

    First, you need to allocate the code of communication with UDP into a separate class, which will be used by a higher-level code. At the same time, this class must contain as little logic as possible and deal only with UDP sending. For example, the logic of receiving an array of bytes and IPAddress must be removed from it. This will allow you to test the maximum amount of code by unit tests, without involving the network. Example:

     public class UDPSender { public void Send(byte[] data, IPAddress address, int port) { UdpClient udpclient = new UdpClient(); udpclient.JoinMulticastGroup(address); IPEndPoint remoteep = new IPEndPoint(address, port); udpclient.Send(data, data.Length, remoteep); udpclient.Close(); } } ... byte[] number = Encoding.ASCII.GetBytes(numb.ToString()); IPAddress multicastaddress = IPAddress.Parse(_instance.configuration.ip); var sender = new UDPSender(); sender.Send(number, multicasaddress, _instance.configuration.port); 

    Secondly, since our new class contains a minimal amount of trivial code, you can not write tests on it, but do a couple of manual checks. If you still want to write tests, but you will need to write complete integration tests using the network and creating a test client.