2017-04-04 18 views
2

我有這些接口起訂量爲單線多個屬性代碼

public interface Interface1 { Interface2 Items {get;} } 
public interface Interface2 { Guid? ApplicationTypeId { get; } } 
public interface Interface3 { Class1 Item {get;} } 
public interface Interface4 { Guid? ApplicationId { get; set; } } 

甲類繼承的第一接口

public class Class1 : Interface1 { 
    public Interface2 Items { get; } 
} 

它由少數的GUID另一類

public static class ContentTypeIds 
{ 
    public static Guid ContentGuid1 => new Guid("{11798e9d-a167-4cfc-8cfa-9a24fd6caf25}"); 

    public static Guid ContentGuid2 => new Guid("{7d22f5bb-37fd-445a-b322-2fa1b108d260}"); 
} 

我需要以單元測試以下屬性

private readonly Interface3 _interface3; 
public Ticket Current 
{ 
    get 
    { 
     //This line is very complicated 
     Interface4 itemByContentType = _interface3.Item?.Items.GetItemByContentType(ContentTypeIds.ContentGuid2); 
     if (itemByContentType?.ContentId != null) 
      return Get(itemByContentType.ContentId.Value); 
     return null; 
    } 
} 

我的測試類放在這裏

[Test] 
public class TestClass { 
    var mock1 = new Mock<Interface1>(); 
    var mock2 = new Mock<Interface2>(); 
    var mock3 = new Mock<Interface3>(); 

    mock1.SetupAllProperties(); 
    mock2.SetupAllProperties(); 
    mock3.SetupAllProperties(); 
} 

爲 'itemByContentType' 的值變爲零。 任何人都可以幫助我簡化測試,因爲測試這個屬性越來越複雜嗎?我正在使用Moq。我會感謝任何幫助。

感謝

回答

0

我不是起訂量方面的專家,但它看起來像它的SetupAllProperties方法簡單地設置了所有的屬性,像性質(即它創建的對象有一個持久的材料,其能夠支持GET/SET操作)。如果沒有完成,那麼據我瞭解,這些屬性仍然可用,但它們將始終解決爲null。這在準備Mock對象時非常方便,但是它本身並沒有設置具有任何價值的屬性。

我認爲你應該使用起訂量的SetupGet返回結合方法與特定值準備項目屬性的GET做。

下面是一些(簡化的)示例代碼,以證明這一點:

public interface IFoo { Guid? ApplicationId { get; set; } } 
public interface IBar { IFoo Items { get; } } 

class Program 
{ 

    static void Main(string[] args) 
    { 
     // SETUP 
     // Prepare mocks 
     Mock<IFoo> MockFoo = new Mock<IFoo>(); 
     Mock<IBar> MockBar = new Mock<IBar>(); 

     // Seting up properties allows us read/write Foo's ApplicationId 
     MockFoo.SetupAllProperties(); 

     // The mocked Foo object should be what's returned when Items is requested 
     var expectedFoo = MockFoo.Object; 

     // Setup the Bar object to return that mocked Foo 
     MockBar.SetupGet(x => x.Items).Returns(expectedFoo); 

     // The value written here will be persistent due to SetupAllProperties 
     expectedFoo.ApplicationId = new Guid("{7d22f5bb-37fd-445a-b322-2fa1b108d260}"); 




     // ACTION 
     // When the "Items" property is accessed, the IFoo we get should be what we mocked... 
     var actualFoo = MockBar.Object.Items; 

     // ... and we can read the value set to Foo's ApplicationId 
     var actualAppId = actualFoo.ApplicationId; 
    } 
} 
+0

由於史蒂芬。簡化我的測試代碼後,我的問題變得更簡單了 –