vendredi 24 juin 2016

How do I improve this class/method for testability?

I have something like this in my application (there's more to it, but I abbreviated to get to the core of the issue:

public class MyClass
{
    // other stuff here...

    public string GetUpdatedCode()
    {
        string nonce = Guid.NewGuid().ToString("N");
        string unixTimeStamp = new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds();
        return $"MySpecialCode/{nonce}/{unixTimeStamp}";
    }
}

The method gets called from elsewhere in the application from an instance, like so:

var newCode = myClassObject.GetUpdatedCode();

The caller doesn't care how the code gets generated, but business requirements dictate that there has to be a Unix timestamp, as well as a random nonce value. I choose to implement the nonce with Guid.New() because it was easy (but I suppose there may be other ways), but the unix timestamp is a hard requirement, and it has to be based on current date and time.

The issue is unit testing the method GetUpdatedCode(). It would be great to be able to predict the output based on a specific datetime, but I'm not sure it makes sense to change the method to GetUpdatedCode(DateTime dateAndTime, Guid nonceGuid) because I don't think it makes sense for calling functions to have to supply or care about that. And then there's the dependency on Guid.NewGuid(), which I'm not sure how to best overcome.

I could inject some _customDateTimeProvider variable via constructor or property injection, but I'm not sure that is appropriate either (or perhaps overkill).

Any advice on how this could be improved for testability, without sacrificing business requirements?

Aucun commentaire:

Enregistrer un commentaire