Should I mock the following example

I am relatively new to using TDD and have recently read about scoffing objects. I have the following test to test the method that gave the date next Saturday.

[TestMethod()]
        public void NextSaturdayTest()
        {
            DateTime date = new DateTime(); 
            date = DateTime.Parse("2010-08-14");
            DateTime expected = new DateTime(); 
            expected = DateTime.Parse("2010-08-21");
            DateTime actual;
            actual = DateExtensions.NextSaturday(date);
            Assert.AreEqual(expected, actual);

            date = DateTime.Parse("2010-08-19");
            expected = DateTime.Parse("2010-08-21");
            actual = DateExtensions.NextSaturday(date);
            Assert.AreEqual(expected, actual);
        }

Does this mean good testing methods in the beginning? Secondly, what is the advantage of using a mock structure to create this test?

Let me know if I can provide more information.

Thanks for any thoughts.

+5
source share
4 answers

First, do not do this:

DateTime date = new DateTime();
date = DateTime.Parse("2010-08-14");

datetime, , , datetime.Remember, .

-, . , ReturnsCorrectNextSaturdayGivenAWednesday, ReturnsCorrectNextSaturdayWhenCrossesEndOfMonth ReturnsCorrectNextSaturdayWhenCrossesEndOfYear.

, , . , DateExtensions (, ), . DateExtensions + Data Access DateExtensions , , .

+7

Mocking .

. , IDataLayer ( )

public class UserService
{
    public UserService(IDataLayer layer) {}
    public User GetById(int id)
} 

. . IDataLayer, UserService. , UserService , .

. , ( )

+5

.

. :

[TestMethod()]
    public void NextSaturdayTest()
    {
        DateTime actual = DateExtensions.NextSaturday(DateTime.Parse("2010-08-14"));
        Assert.AreEqual(DateTime.Parse("2010-08-21"), actual);

        actual = DateExtensions.NextSaturday(DateTime.Parse("2010-08-19"));
        Assert.AreEqual(DateTime.Parse("2010-08-21"), actual);
    }
+2

, , . , - (, DateProvider - ), DateTime .

I would, however, clear your test. You should stick to testing one thing for each method, because if this testing method fails, you will find out WHY it failed, instead of checking the statements and wondering if the rest of them passed.

[TestMethod()]
public void NextSaturdayReturnsCorrectValueStartingFromASaturday()
{
    DateTime date = DateTime.Parse("2010-08-14");

    DateTime expected = DateTime.Parse("2010-08-21");
    DateTime actual = DateExtensions.NextSaturday(date);

    Assert.AreEqual(expected, actual);
}

[TestMethod()]
public void NextSaturdayReturnsCorrectValueWithinTheSameWeek() 
{
    DateTime date = DateTime.Parse("2010-08-19");
    DateTime expected = DateTime.Parse("2010-08-21");
    DateTime actual = DateExtensions.NextSaturday(date);

    Assert.AreEqual(expected, actual);
}

And, as others have suggested, continue to expand your test class to include checks on some stranger situations you might encounter.

+2
source

All Articles