我有以下课程
namespace Foo.Bar.Services
{
public abstract class Service
{
public Service(IUnitOfWork unitOfWork)
{
this.UnitOfWork = unitOfWork;
}
protected IUnitOfWork UnitOfWork { get; private set; }
}
}
using...
namespace Foo.Bar.Services
{
public class ControlService : Service
{
...
private readonly IRepository<GroupStructure> groupStructures = null;
public ControlService(IUnitOfWork uow) : base(uow)
{
...
this.agencyGroupStructures = this.UnitOfWork.GetRepository<AgencyGroupStructure>();
}
public Tuple<bool, int> HasExternalImage(int branchId)
{
var externalResultList = from a in this.Structures.Table
where a.GroupID == branch.GroupID
&& (a.AreExternalRequired == true)
&& (a.ProductTypeID == ETourType.Trailer)
&& !a.Deleted
select a;
return (some logic based on above...)
}
}
并测试
namespace ControlTests
{
[TestFixture]
public class Control
{
//unable to create service due to being abstact
[Test]
public void TestMethod1()
{
******Changed here******
var Mock = new Mock<GroupStructureService> { CallBase = true };
var fakeControl = new ControlService(Mock.Object)
var sut = fakeControl.HasExternalImage(1249);
Assert.That(sut.Item1, "true");
}
}
}
使用NUnit和Moq运行以上操作会显示以下消息:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException:可以 不实例化类的代理:Foo.Bar.Services.ControlService。
找不到无参数的构造函数。
我已经尝试了一些方法,但是无法获得这个未经测试的应用程序来创建要测试的模拟对象
编辑,谢谢。所以我将其更改为使用ControlService并模拟1 依赖。但是它的错误是它不能从 .... GroupStructure到Foo.Bar.IUnitOfWork
答案 0 :(得分:2)
通常,不模拟被测系统。模拟其依赖项并将其注入到被测类的实例中
[TestFixture]
public class Control {
[Test]
public void TestMethod1() {
//Arrange
var repository = new Mock<IRepository<GroupStructure>>();
//...Set up the repository behavior to satisfy logic
var uow = new Mock<IUnitOfWork>();
uow.Setup(_ => _.GetRepository<AgencyGroupStructure>())
.Returns(repository.Object);
var sut = new ControlService(uow.Object);
var expected = true;
//Act
var actual = sut.HasExternalImage(1249);
//Assert
Assert.AreEqual(actual.Item1, expected);
}
}
参考Moq Quickstart,以更好地了解如何使用模拟框架。