mightycode Newton
mightycode Newton

Reputation: 3949

Unit testing toString method

I try to unit tes a Tostring method:

So I have this code:

public class Parcel
{
 //Working
}

Upvotes: 0

Views: 891

Answers (2)

SomeBody
SomeBody

Reputation: 8743

You write: "And I just want to unit test the first criteria of the method CreateDepartmentValue." In that case, don't test the ToString() method, but test the value of your Department property. Your test becomes more stable, because otherwise if you change your ToString() method, you will have to change your test, although you are only interested in the value of your Deptartment property.

Your test might look like this:

[Test, Pairwise]
public void DepartementShouldDependOnWeight(
       [Values(1.0m, 1.01m, 10.0m, 10.01m)]decimal weight,
       [Values("Mail","Regular","Regular","Heavy")]string expectedDepartment)
{
    var parcel = new Parcel { Weight = weight, Value = 0 };
    Assert.AreEqual(parcel.Department, expectedDepartment);
}

Upvotes: 1

keuleJ
keuleJ

Reputation: 3486

You should write your test like this:

[Test]
public void ParcelsUpToWeightOneKGShouldBeDepartmentMail()
{
    var parcel = new Parcel { Name="pacel ", PostalCode="2582Cd", Weight= 0.02m, Value=0.0m};          
         
    Assert.Equal("Name: pacel - Postal code 2582Cd - Weight 0.02 - Value 0.0 - Department Mail", parcel.ToString());
}

The ToString() method returns a string, but does not change the state of parcel. So you should check the returned value.

Upvotes: 1

Related Questions