I have a text file full of unsolved sudoku puzzles. I want to solve each puzzle with my algorithm and compare against a already working solver (from Nuget). For this, I would like to use NUnit and furthermore create a OneTimeSetUp that adds each puzzle to a List, so I can iterate over it and solve it. So far my approach looks like this:
namespace SudokuSolverApp.SudokuSolverTests
{
[SetUpFixture]
public class Config
{
[OneTimeSetUp]
public List<string> Init()
{
var sudokuPuzzles = new List<string>();
var text = System.IO.File.ReadAllLines("/");
for (var index = 0; index < text.Length; index )
{
var puzzle = text[index];
sudokuPuzzles.Add(puzzle);
}
return sudokuPuzzles;
}
}
[TestFixture]
public class SudokuUnitTests
{
public void TestAllSolutions()
{
foreach (var puzzle in sudokuPuzzles)
{
}
}
}
}
However, this does not work, because the program does not recognize the sudokuPuzzles
variable in the last forloop. How would a properly written unit test look like in my case?
CodePudding user response:
As @funatparties points out, you are trying to access a non-existent variable in your test class. There are other problems as well, which I'll list
As stated, there's no variable
SudokoUnitTests.sudokuPuzzles
, so your program can't compile.Even if there were such a variable, there's no reason to expect that NUnit would set it before calling your program. Read the NUnit docs!
OneTimeSetUp methods don't return anything - they are void. Again: docs!
SetUpFixtures are not designed to provide data to tests but to set up an environment to support the tests. They are used for things like creating and populating a database or turning on some big piece of hardware you want to use in your tests. (Maybe not so clear in the docs.)
There are so many things in the above that should not even compile that it makes me wonder. Are you using a real old version of NUnit, which doesn't even know about SetUpFixture? If that were the case, it would just be silently ignored.
Alternatives:
Use a OneTimeSetUp method in your test fixture rather than a SetUpFixture. You can then save the list of puzzles as a member of the class and access it from each test.
If you only have one test method, which loops over each puzzle, t hen you may as well use a SetUp method rather than a OneTimeSetUp.
As a more advanced approach, you could have a separate test for each puzzle, taking the puzzle text as an argument. That's what I would do. But you need to know more about NUnit before doing that, so I suggest saving it for a later improvement.