【发布时间】:2017-11-24 14:01:38
【问题描述】:
我正在编写一个简单的应用程序来学习新技术。我一直在为我的应用程序编写单元测试:
[Test]
public void LessonChangeSubjectShouldNotAffectFormerSubjectPersistence()
{
// given
Lesson ExampleLesson = TestDataFactory.CreateLesson();
Save(ExampleLesson);
Refresh(ref ExampleLesson);
Subject formerSubject = ExampleLesson.Subject;
// when
Subject subject = TestDataFactory.CreateSubject();
_subjectService.Save(subject);
ExampleLesson.ChangeSubject(subject);
Update(ExampleLesson);
_subjectService.Update(formerSubject);
Refresh(ref ExampleLesson);
formerSubject = _subjectService.Get(formerSubject.Id);
subject = _subjectService.Get(subject.Id);
// then
ExampleLesson.Subject.Should().Be(subject);
formerSubject.Should().NotBeNull();
formerSubject.Lessons.Should().NotContain(ExampleLesson);
Refresh(ref ExampleLesson);
_subjectService.Delete(formerSubject);
Refresh(ref ExampleLesson);
Delete(ExampleLesson);
}
这个场景包括:
- 使用默认随机主题创建课程并保存
- 创建新主题并将课程主题更改为新主题
- 检查旧主题是否仍然存在
这个场景成功了,但是当涉及到清理测试时,最后一行出现错误
NHibernate.PropertyValueException : 非空属性引用空值或瞬态值 Register.Core.Model.Lesson.Subject
Lesson类中的Subject字段映射如下:
References(x => x.Subject)
.Cascade.SaveUpdate()
.Column("SubjectId")
.Fetch.Select()
.ForeignKey("FK_Lessons_Subjects")
.Index("IX_Subject")
.LazyLoad()
.Not.Nullable();
Subject 类中的 Lessons 集合映射为:
HasMany(x => x.Lessons)
.Access.CamelCaseField(Prefix.Underscore)
.Cascade.All()
.Fetch.Select()
.ForeignKeyConstraintName("FK_Lessons_Subjects")
.Inverse()
.KeyColumn("SubjectId")
.Not.KeyNullable()
.LazyLoad();
当我交换时
_subjectService.Delete(formerSubject);
与
Refresh(ref ExampleLesson);
Delete(ExampleLesson);
没有来自 NHibernate 的投诉和测试通过。我很好奇发生了什么以及为什么顺序很重要。如果有人能指出我的问题的解决方案,我也将不胜感激。提前谢谢你。
【问题讨论】:
-
@RadimKöhler 现在删除
formerSubject也会删除 ExampleLesson,这是不正确的行为,因为我们将主题更改为另一个 -
@RadimKöhler 它之前得到了一个新的父母,因为测试将课程更改为新的课程并保存它。课程在旧课程被删除之前获得新父母。
标签: c# nhibernate fluent-nhibernate nunit