我是Asp.net 5的新手,对单元测试有疑问。
我要测试的课程如下
while (values.hasNext()) {
IntWritable val = values.next();
...
}
TargetRepository是
public class TargetController : Controller
{
private readonly ITargetRepository _targetRepository;
public TargetController(ITargetRepository targetRepository)
{
this._targetRepository = targetRepository;
}
// GET: /<controller>/
public IActionResult Index()
{
return this.View("Index");
}
}
,TargetContext是
public class TargetRepository : ITargetRepository
{
private readonly TargetContext _context;
public TargetRepository(TargetContext context)
{
this._context = context;
}
}
测试代码是
public class TargetContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString = Startup.Configuration["Data:TargetContextConnection"];
optionsBuilder.UseSqlServer(connectionString);
base.OnConfiguring(optionsBuilder);
}
}
问题如下。在TargetContext中,我使用了
public class TargetControllerTests
{
private readonly TargetController _controller;
public TargetControllerTests()
{
this._controller = new TargetController(new TargetRepository(new TargetContext()));
}
[Fact()]
public void IndexActionResultTest()
{
ViewResult vr = this._controller.Index() as ViewResult;
Assert.NotNull(vr);
Assert.Equal("Index", vr.ViewName);
}
}
获取数据库连接字符串,该字符串在Startup.cs文件中定义。因为我只是在TargetController中测试Index函数,所以我没有运行Startup.cs。结果,我获得了Startup.Configuration的NULLException。我想知道如何解决这个问题并运行我的单元测试。
谢谢。
答案 0 :(得分:0)
使用Moq,您的测试应如下所示:
public class TargetControllerTests
{
private readonly Mock<ITargetRepository> _targetRepository;
private readonly TargetController _controller;
public TargetControllerTests()
{
_targetRepository = new Mock<ITargetRepository>();
this._controller = new TargetController(_targetRepository.Object);
}
[Fact()]
public void IndexActionResultTest()
{
ViewResult vr = this._controller.Index() as ViewResult;
Assert.NotNull(vr);
Assert.Equal("Index", vr.ViewName);
}
}