I am trying to create a fake list of data containing the class ClassA.
ClassA has several properties and one of them is CreatedAt, which is a Datetime, with only a Getter.
For test purposes I want to create a list, populate it with ClassA and define the Datetimes of each CreatedAt-property, but I cant, since it doesnt have a setter:
// Create list
List<ClassA> fakeClassAList = new List<ClassA>(new ClasssA[100]);
// Create random date
DateTime start = DateTime.Today.AddDays(-3);
Random gen = new Random();
int range = ((TimeSpan) (
DateTime.Today
- start)).Days;
// Populate it (This I cant)
foreach(var element in fakeClassAList){
element.CreatedAt = start.AddDays(rand.Next(range));
}
Is the only solution to add a setter or is there a way around that I am currently missing?
As you can see, I dont want to have a setter as it is only being set in my Integrationtests…
using xUnit btw.
I’m guessing you have code such as:
createdAt = DateTime.Now;
You can wrap it in a testable abstraction
https://stackoverflow.com/questions/2425721/unit-testing-datetime-now
Create a TestableClassA that inherits from ClassA and takes the date in the constructor. Might have to mess with accessibility, but at least you won’t break any existing behavior.
All you’ve done here is create a list and initialised it to 100 null values – you’ve not created a single instance of ClassA.
What you need to do is create your 100 instances of ClassA and then you could pass CreateAt into the constructor. For example:
And then ClassA would look something like:
Shouldnt I be able to do this without touching the code outside the testproject?
C# devs
null reference exceptions