2015-09-09 63 views
6

我正在使用我們的服務中實現AutoMapper,並在單元測試中看到一個令人困惑的問題。如何在請求子類時停止Automapper映射到父類

首先這個問題涉及到以下對象和它們各自的地圖:

public class DbAccount : ActiveRecordBase<DbAccount> 
{ 
    // this is the ORM entity 
} 

public class Account 
{ 
    // this is the primary full valued Dto 
} 

public class LazyAccount : Account 
{ 
    // this class as it is named doesn't load the majority of the properties of account 
} 

Mapper.CreateMap<DbAccount,Account>(); 
//There are lots of custom mappings, but I don't believe they are relevant 

Mapper.CreateMap<DbAccount,LazyAccount>(); 
//All non matched properties are ignored 

它還涉及到這些對象,雖然我還沒有在這一點上與AutoMapper映射這些:

public class DbParty : ActiveRecordBase<DbParty> 
{ 
    public IList<DbPartyAccountRole> PartyAccountRoles { get; set; } 
    public IList<DbAccount> Accounts {get; set;} 
} 

public class DbPartyAccountRole : ActiveRecordBase<DbPartyAccountRole> 
{ 
    public DbParty Party { get; set; } 
    public DbAccount Account { get; set; } 
} 

這些類別使用​​包含以下內容的自定義代碼進行轉換,其中source是DbParty:

var party = new Party() 
//field to field mapping here 

foreach (var partyAccountRole in source.PartyAccountRoles) 
{ 
    var account = Mapper.Map<LazyAccount>(partyAccountRole.Account); 
    account.Party = party; 
    party.Accounts.Add(account); 
} 

我有一個問題的測試創建一個新的DbParty,2個新的DbAccounts鏈接到新的DbParty,2個新的DbPartyAccountRoles都鏈接到新的DbParty,每個鏈接到每個DbAccounts。 然後通過DbParty存儲庫測試一些更新功能。如果需要的話,我可以包含一些代碼,它只需要一些時間來擦洗。

當自身運行這個測試工作得很好,但在相同的會話中另一個測試運行時(我將在下面詳細)在上述的轉換代碼映射器調用拋出此異常:

System.InvalidCastException : Unable to cast object of type '[Namespace].Account' to type '[Namespace].LazyAccount'. 

另一個測試也會創建一個新的DbParty,但只有一個DbAccount,然後創建3個DbPartyAccountRoles。我能夠縮小這個測試下來,打破了其他測試的確切行,它是:

Assert.That(DbPartyAccountRole.FindAll().Count(), Is.EqualTo(3)) 

註釋掉這一行允許其他測試通過。

有了這些信息,我的猜測是測試打破了,因爲與調用AutoMapper時DbAccount對象後面的CastleProxy有關,但我沒有絲毫的想法。

我現在已經設法運行相關的功能測試(對服務本身進行調用),它們似乎工作正常,這使我認爲單元測試設置可能是一個因素,最值得注意的是測試問題是針對內存數據庫中的SqlLite運行的。

+0

我正在尋找正在創建問題的確切測試過程。 – Phaeze

+0

我已經找到了確切的測試,甚至在該測試中的確切線,我已經重寫了這個問題來清理它添加更多的上下文 – Phaeze

回答

0

該問題最終與單元測試中多次運行AutoMapper Bootstrapper有關;該調用位於我們測試基類的TestFixtureSetup方法中。

的修復是在創建映射之前添加以下行:

Mapper.Reset(); 

我仍然好奇,爲什麼這是一個有問題的唯一地圖。