如何为DateTimeOffset数据类型赋值

时间:2014-08-19 20:11:55

标签: c# datetime datetimeoffset

对于noob问题,我很抱歉,我正在努力学习TDD。我有一个程序会检查是否使用了特定的时间。我已经使用DateTimeOffset DataType声明了时间,我不确定如何在测试中引用它。这是我的代码。

型号:

namespace Attendance.Models
{
    public class Student
    {
        public string Name { get; set; }
        public DateTime DOB { get; set; }
        public string DayOfWeek { get; set; }
        public int Age { get; set;}
        public DateTimeOffset Time { get; set; }
        public string StreetAddress { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
        public string HomePhone { get; set; }
    }
}

测试控制器:

[TestMethod]
        public void FindByTimeSlotReturnsStudentsInSlot()
        { 
            // Arrange
            var StudentRepository = Mock.Create<Repository>();
            Mock.Arrange( () => StudentRepository.GetAll()).Returns(
                new List<Student>()
        {
            new Student {Name = "Bob Smith", DayOfWeek = "Monday", Time = "10:40:00" },
            new Student {Name = "Mike Jones", DayOfWeek = "Wednesday", Time = "11:20:00" },
            new Student {Name = "Mary Jane", DayOfWeek = "Wednesday", Time = "11:20:00" },
            new Student {Name = "Albert Einstein", DayOfWeek = "Tuesday", Time = "12:15:00" },
            new Student {Name = "Fred Flintsone", DayOfWeek = "Monday", Time = "10:40:00" },
        }).MustBeCalled();

            // Act
            HomeController controller = new HomeController(StudentRepository);
            ViewResult viewResult = controller.FindByDayOfWeek("Monday");
            var model = viewResult.Model as IEnumerable<Student>;

            // Assert
            Assert.AreEqual(2, model.Count());
            Assert.AreEqual("Bob Smith", model.ToList()[0].Name);
            Assert.AreEqual("Monday", model.ToList()[0].DayOfWeek);

错误发生在Time =&#34; 10:40:00&#34;上,它告诉我无法将DateTime转换为字符串。我也尝试了10,40,00,(意外的整数)和10:40:00(语法错误&#34;,&#34;预期)

任何想法都会很棒。

1 个答案:

答案 0 :(得分:2)

Time属性不是DateTime;它是一个DateTimeOffset。使用该类型的构造函数创建类型的实例:

http://msdn.microsoft.com/en-us/library/system.datetimeoffset.datetimeoffset(v=vs.110).aspx

...
new Student {Name = "Bob Smith", DayOfWeek = "Monday", Time = new DateTimeOffset(/*some arguments here*/) }
...