It is unclear, where requiredResidency
is declared. That makes it a little hard to give an answer.
Now, what I have seen (and done) in actual projects are these:
Inheritance
Functionality, that is common to a set of tests is drawn into a "TestBase".
Example:
public abstract class ResidencyTestBase
{
protected Residency GetRequiredResidency( IEnumerable<Residency> testResidencies, Guid testGuid )
{
// TODO Implementation
}
}
// and then you'd have various tests like
public class SomeResidencyTest : ResidencyTestBase
{
[Fact] // we are using xUnit but the idea applies to other
// Test Frameworks, too.
public void SomeTest()
{
var sut = GetRequiredResidency( testData, testId );
// ...
}
}
public class SomeOtherResidencyTest : ResidencyTestBase
{
[Fact] // we are using xUnit
public void SomeOtherTest()
{
var sut = GetRequiredResidency( testData, testId );
// ...
}
}
"TestHelper" class(es)
Example:
public static class ResidencyTestHelper
{
// maybe as extension method on the test data?
public static Residency GetRequiredResidency(this IEnumerable<Residency> testData, Guid testId)
{
// impl.
}
}
// Usage
var sut = testData.GetRequiredResidency( testId );
Your specific functionality
foreach (Residency residency in test.Residencies)
{
if (residency.TestGuid == testGuid) // can be expressed as a LINQ Where
{
if (requiredResidency == null)
requiredResidency = residency; // Sideeffect!
else if (requiredResidency.StartDate < residency.StartDate)
requiredResidency = residency;
// Missing case: both conditions fail ...
}
}
So, I guess one could refactor this like so:
// As ExtensionMethod:
// We _return_ the reference, because we cannot rely on sideeffects
static Residency? GetRequiredResidency ( this Residency? requiredResidency,
IEnumerable<Residency> testData, Guid testId )
{
// Linq is used here, but this can also be expressed in plain old syntax
var residenciesById = testData.Where(r => r.TestGuid == testGuid);
if( requiredResidency is not null )
residenciesById = residenciesById.Where(r => requiredResidency.StartDate < r.StartDate );
return residenciesById.LastOrDefault() ?? requiredResidency;
// ^^ this is to make the behavior the same. If both conditions fail
// (= "missing case" in your code, your code does not change the
// original, so) we get null here, so we set what it originally was.
}
// Usage
Residency requiredResidency = ...; // Assume declared somewhere...
requiredResidency = requiredResidency.GetRequiredResidency( test.Residencies, testId );