1

So basically I am trying to run a unit test on one of the classes in my program, the method in the class works fine but for some reason I can't get the unit test to pass.

Here is my class:

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);
    }

}

} `

Here is my test class:

 [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);        


    }
}

Despite the strings coming back the same I get this error as the reason the test is failing.

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)>.

What is it I am doing wrong?

Thanks

2
  • 6
    You did Convert.ToString(TestDriver); but didn't assign it to a variable, just do Assert.AreEqual(expected, TestDriver.ToString());. Commented May 4, 2018 at 17:13
  • Much appreciated Blake, its crazy how my eyes had overlooked that so many times. Commented May 4, 2018 at 17:16

1 Answer 1

3

The issue with your unit test is that you are comparing string and object.
You should do either this:

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

Or this:

string testValue = Convert.ToString(TestDriver);
Assert.AreEqual(expected, testValue );  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.