There is huge legacy class MyService
in which several new business cases need to be implemented. Unfortunately we are not allowed to touch existing legacy code within _legacyMethod
and need to build a new condition on top of it. However I'd like to have a new code covered with unit tests (using NUnit
)
public class MyService
{
public bool Execute()
{
return _newMethod() && _legacyMethod();
}
protected virtual bool _newMethod()
{
// some business logics
return true;
}
protected virtual bool _legacyMethod()
{
// hundreds of lines of code
return false;
}
}
So primarily my goals were:
- Leave legacy method protected
- Cover new methods with unit tests
- Cover integration of new methods with legacy code
To achieve this I built a proxy within test class:
using NUnit.Framework;
[TestFixture]
public class MyServiceTests
{
private MyServiceProxy _sut;
[SetUp]
public void SetUp()
{
_sut = new MyServiceProxy();
}
[TearDown]
public void TearDown()
{
_sut = null;
}
[Test]
[TestCase(true, true, true)]
[TestCase(false, true, false)]
[TestCase(true, false, false)]
[TestCase(false, false, false)]
public void Execute_ReturnsExpected(bool newMethodStub, bool legacyMethodStub, bool expectedResult)
{
_sut.LegacyMethodStub = legacyMethodStub;
_sut.NewMethodStub = newMethodStub;
var result = _sut.Execute();
Assert.AreEqual(expectedResult, result);
}
[Test]
public void NewMethod_ReturnsTrue()
{
var result = _sut.NewMethodProxy();
Assert.That(result, Is.True);
}
public class MyServiceProxy : MyService
{
public virtual bool NewMethodProxy()
{
return base._newMethod();
}
public bool? NewMethodStub { get; set; }
public bool? LegacyMethodStub { get; set; }
protected override bool _newMethod()
{
if (NewMethodStub.HasValue)
{
return NewMethodStub.Value;
}
return base._newMethod();
}
protected override bool _legacyMethod()
{
if (LegacyMethodStub.HasValue)
{
return LegacyMethodStub.Value;
}
return base._legacyMethod();
}
}
}
In such a way I managed to have a separate set of tests for new method itself, and another one - for integration old-new logics within Execute
method.
Could you advice please if this approach is applicable or can be simplified/improved somehow?