I am a newbie dev and I am trying to create a unit test for the code below. Mind you the code isnt perfect as I have written it in the context of what I have read/learnt so far. Its a program meant to display the prime factors of a number entered by a user. In my unit test file, i created an object of class PFGen but for some reason i am not able to use the object to call method PrimeFactors (which returns an array). Will appreciate all help.
using System;
using static System.Console;
using System.Diagnostics;
using System.IO;
namespace PrimeFactorsGen
{
public class PFGen
{
public static Array PrimeFactors(int number)
{
int[] pf = new int[10];
int position = 0;
for(int div = 2; div <= number; div++)
{
while(number % div == 0)
{
pf[position] = div;
number = number / div;
position = position + 1;
}
}
return pf;
}
public static void RunPrimeFactor()
{
Write("Please enter a value to calculate prime factors: ");
if (int.TryParse(ReadLine(), out int number)){
if(number >= 2)
{
WriteLine($"The prime factors of {number} are: ");
foreach(var entry in PrimeFactors(number))
{
Write($"{entry}, ");
}
}
else
{
WriteLine("Enter a number greater than 2 next time!");
}
}else
{
WriteLine("Enter a valid number");
}
}
static void Main(string[] args)
{
Trace.Listeners.Add(new TextWriterTraceListener(File.CreateText("log.txt")));
Trace.AutoFlush = true;
Trace.WriteLine("Trace is listening...");
RunPrimeFactor();
}
}
}
Thanks for the help so far. I have been able to access PrimeFactors by calling it directly with PFGen. The unit test code is below. It passed.
using System;
using Xunit;
using PrimeFactorsGen;
namespace FactorialUnitTest
{
public class UnitTest1
{
[Fact]
public void Test1()
{
//arrange
int number = 42;
int[] expected = { 2, 3, 7, 0, 0, 0, 0, 0, 0, 0 };
//act
var actual = PFGen.PrimeFactors(number);
//assert
Assert.Equal(actual,expected);
}
}
}
PFGen.PrimeFactors(42);should work, except that the return type ofArrayis a bit unexpected, due to "magic" it will work.PrimeFactorsis declaredstatic, you wouldn't create an instance ofPFGento call it--you would call it asvar output = PFGen.PrimeFactors(input);or similar. * It would be more correct forPrimeFactorsto returnint[]rather thanArray, becauseArrayisn't intrinsically type-safe.