Home > Net >  How to test a static function with an interface as a parameter?
How to test a static function with an interface as a parameter?

Time:06-06

I have seen a code, but I don't know how to set the IPoint2D Start and IPoint2D End which are the GetAngle method's parameters?

public interface IPoint2D
{
        int mX { get; set; }
        int mY { get; set; }

        void Set(int X, int Y);
        string ToString();
}
public static class GeometryAlgorithm
{
   public static double GetAngle(IPoint2D Start, IPoint2D End)
  {
        return Math.Atan2(End.mY - Start.mY, End.mX - Start.mX) / Math.PI * 180.0f;
    }
 }

CodePudding user response:

First, you should define a class implementing this interface. Here is demo code

class Point2D : IPoint2D
{
    public int mX
    {
        get;
        set;
    }

    public int mY
    {
        get;
        set;
    }

    public void Set(int X, int Y)
    {
        mX = X;
        mY = Y;
    }
}

Now you can create instances of this class and pass it to GetAngle method.

Point2D start = new Point2D() { mX = 10, mY = 10 };
Point2D end  = new Point2D() { mX = 20, mY = 20 };
GeometryAlgorithm.GetAngle(start, end);

CodePudding user response:

Interfaces represent a contract between objects. If you want to test your interface you need to create an object that implements the interface.

If you change your IPoint2D to Point2D:

    public class Point2D
    {
        int mX { get; set; }
        int mY { get; set; }

        public Point2D(int x, int y){
            mX = x;
            mY = y;
        }

    }

Then you could use it like so, as long as you also update your static function to take objects of type Point2D:

    //...

    var start = Point2D(0,0);
    var end = Point2D(10,10);

    var angle = GeometryAlgorithm.GetAngle(start,end);

    //...

If you wish to keep it as an interface, you'll have to have it implemented in a class like so:

    public class Point2D : IPoint2D
    {
        int mX { get; set; }
        int mY { get; set; }

        public Point2D(int x, int y){
            mX = x;
            mY = y;
        }

        void Set(int x, int y) {
            mX = x;
            mY = y;
        }

        public override string ToString() {
           return $"X: {mX}; Y: {mY}";
        }
    }

  • Related