简体   繁体   中英

Wicked JUnit Date trick - How would you do this in C#?

Gojko Adzic posted today on his blog about Steve Freeman's unit-testing trick, which helped make it crystal clear why the date comparison in the unit test failed. Here is the blog post describing the trick - it is not long .

The key part of the trick is this method (in Java), which overrides ToString() on a particular instance of the Date class.

private Date namedDate(final String name, final Date date) {
    return new Date(date.getTime()){
        @Override
        public String toString() {
            return name;
        }
    };
}

It appears that this method uses a facility of Java language that doesn't have a match in C# (or at least one that I know of). If you could show me how to do the same trick in C#, that would be awesome.

That is called an anonymous class in Java. It is really just a class implementation with no name, that overrides ToString()

You would be able to the same in C# with a normal, named class - the only problem being, that DateTime is a struct in C#, so you cannot inherit from it.

C# does have anonymous types, but not in the same way as Java. In C# you can have an anonymous type and specify it's properties, but you cannot specify any method implementations. Therefore, anonymous types in C# and Java tends to be used for different things.

Edit

Here is an example on how you would do it in C#, but as stated above, you cannot do it on DateTime (or other struct s, or sealed classes) in C#. So for the sake of the example; I am using an imaginary class called Token, that has a single string property "Value":

private Token GetNamedToken(Token t, string name)
{
    return new NamedToken {Value = t.Value, Name = name};
}

private class NamedToken : Token
{
    public string Name { get; set; }
    public override string ToString()
    {
        return Name;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM