Friday, 8 November 2013

Mock return value only once

Processing records using mock and NUnit


 public List ProcessRecords(IRecordsReader conf)
        {
            var pageHitsResults = new List();
            if (conf != null && conf.HasRecords)
                while (conf.Read())
                {
                    pageHitsResults.Add(
                        new PageHitsResults { Date = conf.GetDateTime("Date"), Hits = conf.GetInt("Hits"), TotalHits = conf.GetInt("TotalHits") });
                } return pageHitsResults;
        }
        [Test]
        public void ProcessRecordsTests()
        {
            var isqlHelperMock = new Mock();
            var iRecordsReaderMock = new Mock();
            iRecordsReaderMock.Setup(x => x.HasRecords).Returns(true);
            int i = 1;
            iRecordsReaderMock.Setup(x => x.Read()).Returns(() => { return i++ == 1; }); var dateTime = DateTime.Now; iRecordsReaderMock.Setup(x => x.GetDateTime("Date")).Returns(dateTime); iRecordsReaderMock.Setup(x => x.GetInt("Hits")).Returns(55); iRecordsReaderMock.Setup(x => x.GetInt("TotalHits")).Returns(123); var pageHitsLogic = new PageHitsLogic(isqlHelperMock.Object); var actual = pageHitsLogic.ProcessRecords(iRecordsReaderMock.Object); Assert.AreEqual(1, actual.Count); Assert.AreEqual(dateTime, actual.First().Date); Assert.AreEqual(55, actual.First().Hits); Assert.AreEqual(123, actual.First().TotalHits);
        }
        [Test]
        public void ProcessRecordsTestsTest()
        {
            var isqlHelperMock = new Mock(); var iRecordsReaderMock = new Mock(); iRecordsReaderMock.Setup(x => x.HasRecords).Returns(true); int i = 1; iRecordsReaderMock.Setup(x => x.Read()).Returns().Returns(() => i++ == 1); var dateTime = DateTime.Now; iRecordsReaderMock.Setup(x => x.GetDateTime("Date")).Returns(dateTime); iRecordsReaderMock.Setup(x => x.GetInt("Hits")).Returns(55); iRecordsReaderMock.Setup(x => x.GetInt("TotalHits")).Returns(123); var pageHitsLogic = new PageHitsLogic(isqlHelperMock.Object); i++;
            // if used here the defalut value of I is 2 and the function for reading does did not yet execued 
            var actual = pageHitsLogic.ProcessRecords(iRecordsReaderMock.Object);
            Assert.AreEqual(1, actual.Count);
            Assert.AreEqual(dateTime, actual.First().Date);
            Assert.AreEqual(55, actual.First().Hits);
            Assert.AreEqual(123, actual.First().TotalHits);
        }