Let's say I have a simple program like
using System;
public class Solution
{
public static void Main(string[] args)
{
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
Array.Sort(arr);
Console.WriteLine(string.Join(" ", arr));
}
}
which I want to test in a separate project like
[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
string input = "2 1";
string expectedOutput = "1 2";
// ... ???
Assert.AreEqual(expectedOutput, actualOutput);
}
Is it possible to do that without actually using the .exe from Solution?
Move the code that does all the work in Main()
to its own class and method:
public static class InputConverter
{
public static string ConvertInput(string input)
{
int[] arr = Array.ConvertAll(input.Split(' '), int.Parse);
Array.Sort(arr);
return string.Join(" ", arr);
}
}
Your Main()
then becomes:
public static void Main(string[] args)
{
var input = Console.ReadLine();
var output = InputConverter.ConvertInput(input);
Console.WriteLine(output);
}
You can now test ConvertInput()
without being dependent by the write and read functions of Console
:
[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
// Arrange
var input = "2 1";
var expectedOutput = "1 2";
// Act
var actualOutput = InputConverter.ConvertInput(input);
// Assert
Assert.AreEqual(expectedOutput, actualOutput);
}
As an aside: the way you are passing in your arguments seems as though you are guaranteeing that the input will always be what you expect it to be. What happens when the user passes in something totally different than string representations of integers? You need to validate the input in InputConverter.ConvertInput()
and create appropriate courses of action based on that (throw an Exception
, return null
, depends on what you're after). You'll then have to unit test those scenarios as well to make sure ConvertInput()
performs as expected for all cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With