我在项目中编写的一些函数返回true \ false,我试图用单元测试来测试它们。
public class DbContextDal : DbContext
{
public DbContextDal() : base("BdContextDal_ConnectionString_appConfig3")
{
Configuration.LazyLoadingEnabled = true;
}
public virtual DbSet<User> users { get; set; }
public virtual DbSet<Student> students { get; set; }
public virtual DbSet<Course> courses { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
}
你可以看到DbContextCal是数据库的连接,我有一些返回值的函数。 在这里,我试图用我为单元测试做的类来测试它
public class Student
{
// variables of this student..
public float getGradeInCourse(Course c)
{
if (s == null || c == null) return -1f;
float grade = -1f;
DbContextDal dal = new DbContextDal();
Enrollment e = dal.Enrollments.Find(s.ID, c.ID);
if (e != null)
grade = e.Grade;
return grade;
}
}
我想测试这个函数getGradeInCourse,我做了单元测试:
[TestClass()]
public class StudentTests
{
[TestMethod()]
public void getGradeInCourseTest()
{
DbContextDal dal = new DbContextDal();
Student s = dal.students.Find(100);
Course c = dal.courses.Find(900);
Assert.AreEqual(s.getGradeInCourse(c), 76);
}
}
我收到此错误:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Migrations is enabled for context 'DbContextDal' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.
在这个DBcontext中,我几乎在我的项目中的每个函数中使用。 我不能在Mocks中使用,因为我在这个对象Dbcontext中多次使用,例如在我试图测试的函数中。
答案 0 :(得分:1)
您可以使用允许它的框架来模拟数据库,而不是使用您的真实数据库,只需修改模拟数据库的行为即可使测试通过。 我为此使用了Typemock隔离器,例如:
[TestMethod,Isolated]
public void TestMethod1()
{
var fakeDBContextDal = Isolate.Fake.NextInstance<DbContextDal>();
var s = new Student();
var c = new Course();
s.ID = 1;
c.ID = 2;
var e = new Enrollment();
e.Grade = 100;
Isolate.WhenCalled(() => fakeDBContextDal.Enrollments.Find(1,2)).WithExactArguments().WillReturn(e);
Assert.AreEqual(s.getGradeInCourse(c), 100);
}