DateTime接口用于单元测试 [英] DateTime Interface to be used for unit testing

查看:109
本文介绍了DateTime接口用于单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经为日期时间创建了这样的接口:

Hi So I have created an interface for datetime like this:

public interface ITimeProvider<T>
{
    T Now { get; }
    string ToShortDateString();
}

然后我对该接口有一个实现:

And then I have one implamentation of that interface like this:

public class DateTimeProvider : ITimeProvider<DateTime>
{

    private DateTime _date;

    public DateTime Now
    {
        get { return DateTime.Now; }
    }

    public  DateTimeProvider()
    {

        _date = new DateTime();
    }
    public string ToShortDateString()
    {
        return _date.ToShortDateString();
    }
}

然后我在主机中使用它并想要使用属性注入,但是我遇到了一些问题,这是我所拥有的一个快照:

Then I am using it in my main unit and want to use property injection but i ran into some problems, here is a snap of what I have:

public class Atm : IAtm
{
   public ITimeProvider _timeProvider { get;set; }
}

这没有用,因为我没有指定类型。我可以做

This doesn't work as I don't specifiy a type. I could just do

public ITimeProvider<DateTime> _timeProvider { get;set; }

但是我将无法使用其他时间提供程序。我还考虑过(并且这是我唯一能想到的解决方案)是使ATM具有通用性,例如

But then I wouldn't be able to use another timeprovider. I have also considered(and is the only solution I could come up with) is to make ATM generic so something like this

 public class Atm<T> : IAtm
 {
      public ITimeProvider<T> _timeProvider { get;set; }
 }

但是后来我觉得我不能使用财产注入,

But then I feel like I can't use property injection, is there any other way I can do this so I will be able to test it?

推荐答案

您要抽象的东西是 DateTime.Now 函数而不是 DateTime 数据类型,您可以使实现保持相同,而只需修复类型即可。

The thing you are abstracting is the DateTime.Now function not the DateTime datatype, you can keep the implementation the exactly the same but just fix the type.

public interface ITimeProvider
{
    DateTime Now { get; }
    string ToShortDateString();
}

public class DateTimeProvider : ITimeProvider
{

    public DateTime Now
    {
        get { return DateTime.Now; }
    }

    public string ToShortDateString()
    {
        return Now.ToShortDateString();
    }
}


public class RemoteTimeProvider : ITimeProvider
{
    public DateTime Now
    {
        get 
        { 
            using(var client = new WebClient())
            {
                var timeString = client.DownloadString(http://www.timeapi.org/utc/now);
                return DateTime.Parse(timeString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToLocalTime()
            }

        }
    }

    public  DateTimeProvider()
    {

    }
    public string ToShortDateString()
    {
        //ToDo
    }
}

此外,我并没有真正得到您的 ToShortDateString()可以,它不接受参数,而仅使用从 new DateTime()返回的值。

Also, I don't really get what your ToShortDateString() does, it does not take in a parameter and it just uses the value returned from new DateTime().

这篇关于DateTime接口用于单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆