c# algorithm to create fake canadian social secutiry number (SIN) for unit tests

algorithm, c#

Solution

There may be a way to algorithmically generate a valid number, but as a quick fix, you could generate a random series of 9 integers, then validate it. Repeat until you have a valid series. Here is a complete implementation:

class SinGenerator
{
    Random r = new Random();

    /// <summary>
    /// Generates a valid 9-digit SIN.
    /// </summary>
    public int[] GetValidSin()
    {
        int[] s = GenerateSin();

        while (!SinIsValid(s))
            s = GenerateSin();  

        return s;
    }

    /// <summary>
    /// Generates a potential SIN. Not guaranteed to be valid.
    /// </summary>
    private int[] GenerateSin()
    {
        int[] s = new int[9];

        for (int i = 0; i < 9; i++)
            s[i] = r.Next(0, 10);

        return s;
    }

    /// <summary>
    /// Validates a 9-digit SIN.
    /// </summary>
    /// <param name="sin"></param>
    private bool SinIsValid(int[] sin)
    {
        if (sin.Length != 9)
            throw new ArgumentException();

        int checkSum = 0;

        for (int i = 0; i < sin.Length; i++)
        {
            int m = (i % 2) + 1;
            int v = sin[i] * m;
            if (v > 10)
                checkSum += 1 + (v - 10);
            else
                checkSum += v;
        }

        return checkSum % 10 == 0;
    }
}

Problem

I need to write unit test in c# to generate fake canadian SIN number for our application. After searching the internet, here is what I found. I don't even know how to get started. Specially multiplying each top number with the number below is confusing me because its not a straight multiplication. Appreciate the help in advance. Thanks. Here is the algorithm I got from the google search. ``` Algorithm _ Social Insurance Numbers are validated via a simple checksum process. Let's use this fictitious SIN to demonstrate: 046 454 286 < Try substituting your SIN 046 454 286 \ Multiply each top number 121 212 121 / by the number below it.. ----------- 086 858 276 < and get this. ^ Notice here that 8*2=16, add 1 and 6 together and get 7. If you get a 2 digit # add the digits together. Add all of these digits together. 0+8+6+8+5+8+2+7+6=50 /\ If the SIN is valid this # will be evenly divisible by 10. This is a 'valid' SIN. ```

Original source