我有应用程序,我在应用程序中使用单元测试。我在单元测试中编写了以下代码。
using NUnit.Framework;
using YTPanel.Models.Repository;
namespace Tests
{
public class StudentTest
{
private readonly StudentRepository repo;
public StudentTest(StudentRepository context)
{
repo = context;
}
[Test]
public void TestList_Default()
{
//var result = repo.GetStudents(1, 8, null).ToList();
//Assert.IsNotNull(result);
Assert.Pass();
}
}
}
我将项目添加到单元测试作为参考。但是,当我运行测试时,由于下面的代码,我失败了
private readonly StudentRepository repo;
public StudentTest(StudentRepository context)
{
repo = context;
}
我的学生存储库类如下
public class StudentRepository
{
private readonly YTContext _db;
public StudentRepository(YTContext context)
{
_db = context;
}
public List<Student> GetStudents(int page, int limit = 8, string query = null)
{
try
{
var skip = (page - 1) * limit;
var students = _db.Students.Where(x => query == null || x.Name.Contains(query) || x.Surname.Contains(query) || x.University.Name.Contains(query) || x.Bolum.Name.Contains(query))
.Include(x=>x.Bolum).Include(x=>x.University)
.Skip(skip).Take(limit).ToList();
return students;
}
catch (Exception ex)
{
return null;
}
}
}
如何从单元测试中获得此课程。我错过了什么 ?
提前致谢
您不应该使用数据库中的实际数据测试代码。我猜这就是你的测试失败的原因。它无法建立与db的连接,因此失败。
您应该模拟您的IStudentRepository并使用您选择假冒的数据测试您的代码 - 从您的回购中返回