lundi 1 août 2016

unit testing body of properties in C#

This is my Code

public class AssistanceRequest : DocumentBase
{
    public AssistanceRequest()
    {
        RequestTime = DateTime.Now;
        ExcecutionTime = DateTime.MaxValue;
    }

    public AssistanceRequest(int amount, string description, DateTime? requestTime) : this()
    {
        //Check for basic validations
        if (amount <= 0)
            throw new Exception("Amount is not Valid");
        this.Amount = amount;
        this.Description = description;
        this.RequestTime = requestTime ?? DateTime.Now;
    }

    private long Amount { get; set; }

    private DateTime requestTime { get; set; }

    public DateTime RequestTime
    {
        get { return requestTime; }
        set
        {
            if (value != null && value < DateTime.Now)
                throw new Exception("Request Time is not Allowed");
            requestTime = value;
        }
    }

As you can see I have a validation in my Set body. I need to test it. and I try to call the constructor in my Tests. but I get Exception in Constructor ( act ) before assertion. How to make my tests right?

This is my Test:

[Theory]
    [MemberData("RequestFakeData")]
    public void Should_Throw_Exception_RequestDate(int amount, string description, DateTime requestDate)
    {
        var manager = new AssistanceRequest(amount,description,requestDate);
        manager.Invoking(x => x.SomeMethodToChangeRequestTime).ShouldThrowExactly<Exception>()
    }

    public static IEnumerable<object[]> RequestFakeData
    {
        get
        {
            // Or this could read from a file. :)
            return new[]
            {
            new object[] { 0,string.Empty,DateTime.Now.AddDays(1) },
            new object[] { 2,"",DateTime.Now.AddDays(-2) },
            new object[] { -1,string.Empty,DateTime.Now.AddDays(-3) },
            };
        }
    }

Aucun commentaire:

Enregistrer un commentaire