0

I have created the DataColumn class. Now I want to do unit test using Moq. How i should write code for this?

 [Serializable]
 public class DataColumn<T> : IDataColumn
 {

    private string columnName = null;

    private T defaultValue;

     public DataColumn(string columnName) : this(columnName, default(T))
     {
     }


    public DataColumn(string columnName, T defaultValue)
    {
        ColumnName = columnName;
        DefaultValue = defaultValue;
     }


    public T DefaultValue
    {
        get
        {
            return defaultValue;
        }

        set
        {
            defaultValue = value;
        }
    }

    public bool IsDefaultValueDefined()
    {
        return ReferenceEquals(defaultValue, default(T));
    }

    public string ColumnName
    {
        get
        {
            return columnName;
        }

        set
        {
            this.columnName = value;
        }
    }

    public Type DataType
    {
        get
        {
            return typeof(T);
        }
    }

    public override string ToString()
     {
         return ColumnName + "[" + DataType.Name + "]" + (IsDefaultValueDefined() ? " (" + DefaultValue + ")" : " ");
     }

How do I create a unit test for this piece of code?

Peter Bratton
  • 6,302
  • 6
  • 39
  • 61
PRV
  • 1

1 Answers1

1

Not sure why you would need Moq to test this, are you trying to Moq this class to test another?

Mock<IDataColumn<T>> dc = new Mock<IDataColumn<T>>();
dc.Setup(s=>s.IsDefaultValueDefined).Returns(true);
someOtherObject.SomeMethod(dc.object);
dc.verfiy(s=>s.IsDefaultValueDefined, Times.Once());
eweb
  • 27
  • 7
  • I want to creat the unit test using moq to test another class. I am creating the class library for tabular database – PRV Feb 28 '14 at 02:52
  • The code above mocks out IDataColumn IsDefaultValueDefined so that it will return true every-time its called. Last line will verify that it was in fact called one time. Hope this example helps – eweb Feb 28 '14 at 19:25
  • Sorry would be some implementing class like string. If T was interfaced, you could even mock that out but typically any stub will do as your not actually testing T – eweb Mar 06 '14 at 15:41