我想知道是否有可能对从Dotnet MVC中的抽象基类继承的控制器进行单元测试?我的控制器看起来像这样:
在下面的安装示例中,我编写测试的方法是MyController。我在NotificationHubClient.CreateClientFromConnectionString()上的DeviceBaseController中遇到问题;我以通常的方式模拟控制器。
public class MyController : BaseNamedController<Class, ClassRepresentation>
{
private readonly IContext _context;
public MyController(IContext context): base(context)
{
_context = context;
}
}
public abstract class BaseNamedController<T, NT> : BaseController<T, NT>
where T : NamedEntity
where NT : NamedEntity
{
public BaseNamedController(IContext context):base(context)
{
}
}
public abstract class BaseController<T, NT> : DeviceBaseController
where T : DeletableEntity
where NT : DeletableEntity
{
protected IContext _context;
public BaseController(IContext context)
{
_context = context;
}
}
public class DeviceBaseController : ApiController
{
private readonly NotificationHubClient _hubSandbox;
public DeviceBaseController()
{
_hubSandbox = NotificationHubClient.CreateClientFromConnectionString(readFromAppSettings)
}
}
这是我的模拟实现:
[TestClass]
public class MyControllerTests
{
private Mock<IContext> _mockContext;
[TestInitialize]
public void SetupTests()
{
_mockContext = new Mock<IContext>();
}
[TestMethod]
public async Task Test_One()
{
var controller = new MyController( _mockContext.Object);
var result = controller.Method(It.IsAny<string>());
}
}
任何主意如何解决这个问题?
问题是密钥不在应用程序设置中,所以我将它们添加到了测试项目的app.config中,并且代码也随之移动。