I'm trying to substitute a method using ForPartsOf<...>()
and then subst.Configure().MyMethod(...).Returns(...)
or subst.When(x => x.MyMethod(..)).Returns(...)
, but in both cases the real MyMethod
gets called. I was under the impression that both Configure()
and When()
was supposed to make sure the MyMethod()
call was made in "configure mode", so that no real call will be made. Am I wrong? Or am I doing something wrong?
Here below is a my (much simplified, and namechanged) code. For both subst1
and subst2
, the real NeedsMoreWork
method gets called with item == null
.
public interface IMyClass
{
bool NeedsMoreWork(Item item, out Part part);
bool DoWork(Item item);
}
public class MyClass : IMyClass
{
private ILogger log;
public MyClass(ILogger log)
{
this.log = log;
}
public bool NeedsMoreWork(Item item, out Part part)
{
log.Debug($"Examining item {item.Id}");
part = null;
if (item.Completed())
{
log.Debug($"Item {item.Id} already completed.");
return false;
}
part = item.GetNextPart();
log.Debug($"Item {item.Id} needs work on part {part.Id}.");
return true;
}
public bool DoWork(Item item)
{
if (!item.NeedsMoreWork(item, out Part part))
return false;
log.Debug($"Starting work on part {part.Id}.");
// Do work on part.
log.Debug($"Work completed on part {part.Id}.");
return true;
}
}
[TestMethod]
public void TestDoWork()
{
// Version with Configure():
var subst1 = Substitute.ForPartsOf<MyClass>(Substitute.For<ILogger>());
subst1.Configure()
.NeedsMoreWork(Arg.Any<Item>(), out Arg.Any<Part>())
.Returns(false);
// Version with WhenForAnyArgs():
var subst2 = Substitute.ForPartsOf<MyClass>(Substitute.For<ILogger>());
subst2.WhenForAnyArgs(x => x.NeedsMoreWork(Arg.Any<Item>(), out Arg.Any<Part>())
.Returns(false);
}