Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6167925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T22:35:52+00:00 2026-05-23T22:35:52+00:00

I am working on a class that utilises a UdpClient, and attempting to learn/utilise

  • 0

I am working on a class that utilises a UdpClient, and attempting to learn/utilise a TDD approach using NUnit and Moq in the process.

A bare-bones part of my class so far is as follows:

public UdpCommsChannel(IPAddress address, int port)
{
    this._udpClient = new UdpClient();
    this._address = address;
    this._port = port;
    this._endPoint = new IPEndPoint(address, port);
}

public override void Open()
{
    if (this._disposed) throw new ObjectDisposedException(GetType().FullName);

    try
    {
        this._udpClient.Connect(this._endPoint);
    }
    catch (SocketException ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

public override void Send(IPacket packet)
{
    if (this._disposed) throw new ObjectDisposedException(GetType().FullName);

    byte[] data = packet.GetBytes();
    int num = data.Length;

    try
    {
        int sent = this._udpClient.Send(data, num);
        Debug.WriteLine("sent : " + sent);
    }
    catch (SocketException ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

.
.
For the Send method, I have the following unit test at the moment:

[Test]
public void DataIsSent()
{
    const int port = 9600;

    var mock = new Mock<IPacket>(MockBehavior.Strict);
    mock.Setup(p => p.GetBytes()).Returns(new byte[] { }).Verifiable();

    using (UdpCommsChannel udp = new UdpCommsChannel(IPAddress.Loopback, port))
    {
        udp.Open();
        udp.Send(mock.Object);
    }

    mock.Verify(p => p.GetBytes(), Times.Once());
}

.
.
I’m not that happy with that because it is using an actual IP address, albeit only the localhost, and the UdpClient inside the class is physically sending data to it. Therefore, this is not a true unit test as far as I understand it.

Problem is, I can’t get my head around exactly what to do about it. Should I change my class and pass in a new UdpClient as a dependency perhaps? Mock the IPAddress somehow?

Struggling a bit, so I need to stop here to see if I am on the right track before carrying on. Any advice appreciated!

(Using NUnit 2.5.7, Moq 4.0 and C# WinForms.)
.
.

UPDATE:

OK, I have refactored my code as follows:

Created an IUdpClient interface:

public interface IUdpClient
{
    void Connect(IPEndPoint endpoint);
    int Send(byte[] data, int num);
    void Close();
}

.

Created an adapter class to wrap the UdpClient system class:

public class UdpClientAdapter : IUdpClient
{
    private UdpClient _client;

    public UdpClientAdapter()
    {
        this._client = new UdpClient();
    }

    #region IUdpClient Members

    public void Connect(IPEndPoint endpoint)
    {
        this._client.Connect(endpoint);
    }

    public int Send(byte[] data, int num)
    {
        return this._client.Send(data, num);
    }

    public void Close()
    {
        this._client.Close();
    }

    #endregion
}

.

Refactored my UdpCommsChannel clas to require an instance of an IUdpClient injected via the constructor:

public UdpCommsChannel(IUdpClient client, IPEndPoint endpoint)
{
    this._udpClient = client;
    this._endPoint = endpoint;
}

.

My unit test now looks like this:

[Test]
public void DataIsSent()
{
    var mockClient = new Mock<IUdpClient>();
    mockClient.Setup(c => c.Send(It.IsAny<byte[]>(), It.IsAny<int>())).Returns(It.IsAny<int>());

    var mockPacket = new Mock<IPacket>(MockBehavior.Strict);
    mockPacket.Setup(p => p.GetBytes()).Returns(new byte[] { }).Verifiable();

    using (UdpCommsChannel udp = new UdpCommsChannel(mockClient.Object, It.IsAny<IPEndPoint>()))
    {
        udp.Open();
        udp.Send(mockPacket.Object);
    }

    mockPacket.Verify(p => p.GetBytes(), Times.Once());
}

.

Any further comments welcome.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T22:35:53+00:00Added an answer on May 23, 2026 at 10:35 pm

    If you want to test only the functionality of your class, the I would go creating an interface ICommunucator, then create a class UdpCommunicator, which directly wraps UdpClient properties and methods needed, without any checks and conditions.

    In your class, inject the wrapper and use is instead of tf UdpClient.

    That way, in the tests you can mock ISender, and test.

    Of course, you will not have tests for the wrapper itself, but if it’s just a plain call forwarding, you do not need this.

    Basically, you have started in the right direction, but you have added some custom logic, which can not be tested that way – so you need to split the custom logic and the comm part.

    I.e., your class becomes like this:

    public MyClass(ICommunicator comm)
    {
         public void Method1(someparam)
         {
             //do some work with ICommunicator
         }
         ....
    }
    

    And your test will look like:

    var mockComm = Mock.GetMock<ICommunicator>();
    mockComm.Setup ....
    var myTestObj = new MyClass(mock.Object);
    MyClass.Method1(something);
    
    mock.Verify....
    

    So, in few Verify statements you can check if Open on the communicator is called, if the right data was passed, etc.

    In general – you do not need to test system or third-party classes, only your own.

    If your code uses such a classes, make them injectable. If these classes do not have virtual methods (i.e. you can not mock them directly), or do not implement some common interface (like SqlConnection, etc. does – it. implements IDbConnection), then you create a plain wrapper like explained above.

    Besides of the testability improvements, such an approach will make it much easier to modify your code in the future – i.e. when you need some other method of communication, etc.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working on a class that inherits from another class, but I'm getting a
I'm working on a class that is storing a 2D array of class MyType
I'm currently working on a class that calculates the difference between two objects. I'm
So I'm working on this class that's supposed to request help documentation from a
I'm working on a sparse matrix class that needs to use an array of
I'm working on some code that uses the System.Diagnostics.Trace class and I'm wondering how
I am working in a project that has two main parts: a class library
I have gotten everything working for my class in which I am using Tomcat
I am working on a class that maintains a dictionary of images. This dictionary
I am working on a class that will implement a client for a certain

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.