如您所见,我编写了以下 linq 查询,它通过将数据连接在一起来创建一个新对象:
var translations = from t in context.Translations
join token in context.Tokens on t.Guid equals token.Guid
join t2 in context.Translations on new { t.Guid, LanguageCode = "fr" } equals new { t2.Guid, t2.LanguageCode} into j //TODO: fr needs to be replaced by the language of the translators account
from j2 in j.DefaultIfEmpty()
where t.LanguageCode == String.Empty
orderby t.Text
select new TranslationView
{
Guid = t.Guid,
LanguageCode = j2.LanguageCode,
SourceText = t.Text,
Translation = j2.Text,
IsNew = j2.Text == null,
Notes = token.Notes,
Required = token.Required,
Type = (Token.TokenType)token.Type,
Location = (Token.LocationType)token.Location
};
问题是我现在正在尝试使用 Rhino.Mocks 编写单元测试,它返回错误Object reference not set to an instance of an object.
所以我现在的问题是,有没有更好的方法可以编写这个查询?一种在实际情况和单元测试情况下都可以工作的方式?
我尝试在位中传递一个值,DefaultIfEmpty()
它使它适用于 Mock,但随后主代码失败。
编辑 单元测试代码:
[Test]
public void Build_Translation_List_TwoItems_Context()
{
//Arrange: Setup context
var context = setupContext();
//Act: Pass the context through
var result = TranslationHelpers.BuildTranslationList(context, 1);
//Result
result.TranslationList.Count.ShouldEqual(2);
result.PagingInfo.TotalItems.ShouldEqual(2);
}
设置上下文方法:
public static ITranslationContext setupContext()
{
var context = new Mock<ITranslationContext>();
context.SetupProperty(x => x.Tokens, new UnitTestHelpers.FakeDbSet<Token>
{
new Token
{
DateAdded = DateTime.Now,
Guid = Guid.Parse("f3099a43-e12d-4ea3-ba06-265fde807f03"),
LastUpdated = DateTime.Now,
Location = (short)0,
Type = (short)0,
LocationDescription = "Test 1",
Notes = "Testing 1",
Required = "Testing"
},
new Token
{
DateAdded = DateTime.Now,
Guid = Guid.Parse("7D6937D8-F7E1-4B92-934E-465683874B65"),
LastUpdated = DateTime.Now,
Location = (short)0,
Type = (short)0,
LocationDescription = "Test 3",
Notes = "Testing 3",
Required = "Testing"
},
});
context.SetupProperty(x => x.Translations, new UnitTestHelpers.FakeDbSet<Translation>
{
new Translation{Guid = Guid.Parse("f3099a43-e12d-4ea3-ba06-265fde807f03"), LanguageCode = String.Empty, Text = "Testing 1"},
new Translation{Guid = Guid.Parse("f3099a43-e12d-4ea3-ba06-265fde807f03"), LanguageCode = "fr", Text = ""},
new Translation{Guid = Guid.Parse("7D6937D8-F7E1-4B92-934E-465683874B65"), LanguageCode = String.Empty, Text = "Testing 3"},
new Translation{Guid = Guid.Parse("7D6937D8-F7E1-4B92-934E-465683874B67"), LanguageCode = "fr", Text = "Testing 4"}
});
return context.Object;
}
任何帮助将非常感激。