我正在尝试为下面的代码编写单元测试,专门用于测试ModelUnderTest类的Calculate方法。尽管有一些尝试和Goolgling我很难过。
问题的关键在于模型使用绑定到另一个类的属性的属性(该属性也绑定在我的实际代码中 - 此处未显示)。该属性在两个类中都是只读的,所以我不能只设置它。
我想模拟(或存根)IService类,但我开始怀疑在这种情况下是否可行。
以下是代码:
using System.Windows;
using System.Windows.Data;
namespace Testing
{
public interface IService
{
int Option { get; }
}
public class ConcreteService : DependencyObject
{
public static readonly DependencyProperty ActiveOptionProperty = DependencyProperty.Register("ActiveOption", typeof(int), typeof(ConcreteService), new PropertyMetadata(null));
public int ActiveOption { get { return (int) GetValue(ActiveOptionProperty); } }
}
public class ModelUnderTest : DependencyObject
{
private readonly IService _service;
public ModelUnderTest(IService service)
{
_service = service;
BindingOperations.SetBinding(this,
CurrentOptionProperty,
new Binding
{
Source = _service,
Path = new PropertyPath(ConcreteService.ActiveOptionProperty)
});
}
public static readonly DependencyProperty CurrentOptionProperty = DependencyProperty.Register("Option", typeof(IService), typeof(ModelUnderTest), new PropertyMetadata(null));
public int Option
{
get { return (int)GetValue(CurrentOptionProperty); }
}
public int Calculate()
{
return Option + 7;
}
}
如果我有这样的测试:
[TestClass]
public class ModelUnderTestTest
{
[TestMethod]
public void Calculate_Test()
{
var service = MockRepository.GenerateStub<IService>();
var target = new ModelUnderTest(service);
// Do something to make target's Option value be '3'
target.Calculate().Should().Be(10);
}
}
我可以做些什么来使这个测试通过?