我的单元测试有什么问题? C#

时间:2018-05-04 17:12:03

标签: c#

所以基本上我试图在我的程序中的一个类上运行单元测试,该类中的方法工作正常,但由于某种原因我无法通过单元测试。

这是我的班级:

public class Driver

{

    public DateTime Date { get; set; }
    public String Start { get; set; }
    public String End { get; set; }
    public int Distance { get; set; }

    public Driver(DateTime date, String start, String end, int distance)
    {
        this.Date = date;
        this.Start = start;
        this.End = end;
        this.Distance = distance;

    }     

    public override String ToString()
    {

        return string.Format("Date: {0}, Start Postcode: {1}, End Postcode: {2}, Distance: {3}miles", this.Date.ToString("dd/MM/yyyy"), this.Start, this.End, this.Distance);
    }

}

} `

这是我的测试类:

 [TestClass]
public class Driverdetailstest
{
    private Driver TestDriver;

    [TestMethod]
    public void DriverDataTest()
    {
        DateTime date = new DateTime(2017, 12, 15);
        string start = ("SR47BB");
        string end = ("SR47FY");
        int distance = 10;


        var expected = string.Format("Date: {0}, Start Postcode: {1}, End Postcode: {2}, Distance: {3}miles", date.ToString("dd/MM/yyyy"), start, end, distance);




        TestDriver = new Driver(date, start, end, distance);
        Convert.ToString(TestDriver);




        Assert.AreEqual(expected, TestDriver);        


    }
}

尽管字符串返回相同但我得到此错误是测试失败的原因。

Message: Assert.AreEqual failed. Expected:<Date: 15/12/2017, Start Postcode: SR47BB, End Postcode: SR47FY, Distance: 10miles (System.String)>. Actual:<Date: 15/12/2017, Start Postcode: SR47BB, End Postcode: SR47FY, Distance: 10miles (TaxiTracker.Driver)>.

我做错了什么?

由于

1 个答案:

答案 0 :(得分:3)

单元测试的问题在于您要比较stringobject 你应该这样做:

Assert.AreEqual(expected, TestDriver.ToString());  

或者这个:

string testValue = Convert.ToString(TestDriver);
Assert.AreEqual(expected, testValue );