2016-12-16 59 views
0

的單元測試的切入點,試圖編寫測試我的應用程序的特定錯誤條件下的條目 - 該條目類似於太:重寫AutoFac註冊記憶應用

IFoo.cs

public interface IFoo 
{ 
    void DoStuff(); 
} 

富。 CS

public class Foo : IFoo 
{  
    void DoStuff() 
    { 
     // Do some things 
    } 
} 

AThing.cs

public class AThing 
{ 

    private readonly IFoo _iFoo; 

    public AThing(IFoo iFoo) 
    { 
     _iFoo = iFoo; 
    } 

    public void Whatever() 
    { 
     _iFoo.DoStuff(); 
    } 
} 

AutoFacConfig.cs

public class AutofacConfig 
{ 
    private static IContainer _container; 

    public static IContainer Container 
    { 
     get { return _container; } 
    } 

    public static void IoCConfiguration() 
    { 
     var builder = new ContainerBuilder(); 

     // Registrations... 
     builder.RegisterType<AThing>(); 
     builder.RegisterType<Foo>().AsImplementedInterfaces(); 

     _container = builder.Build(); 
    } 
} 

的Program.cs

public class Program 
{ 
    public static int Main(string[] args) 
    { 
     try 
     { 
      AutofacConfig.IoCConfiguration(); 
      using (var scope = AutofacConfig.Container.BeginLifetimeScope()) 
      { 
       var aThing = scope.Resolve<AThing>(); 
       var result = aThing.Whatever()); 
      } 
     } 
     catch (Exception ex) 
     { 
      return 0; 
     } 

     return 1; 
    } 
} 

test.cs中

[TestFixture] 
public class Test 
{ 
    [Test] 
    public void ShouldReturn0WhenExceptionEncountered() 
    { 
     // How to override say, Foo.DoStuff to throw an exception? 
     var result = Program.Main(); 

     Assert(0, result); 
    } 
} 

以上是一個簡化的示例,然而,它可能難以實際上會導致異常通過我通過AutoFac註冊的真實實現。爲了測試入口點捕獲異常,如果我可以在Foo之內注入我的一個依賴關係的模擬或僞造,將會更容易。

我該怎麼做?

回答

0

this answer類似我已經做了以下修改來測試我的情景:

重構AutoFacConfig.cs

public class AutofacConfig 
{ 
    private static IContainer _container; 

    public static Action<ContainerBuilder> OverridenRegistrations; 

    public static IContainer Container 
    { 
     get { return _container; } 
    } 
    public static void IoCConfiguration() 
    { 
     var builder = new ContainerBuilder(); 

     // Registrations... 
     builder.RegisterType<AThing>(); 
     builder.RegisterType<Foo>().AsImplementedInterfaces(); 

     OverridenRegistrations(builder); 

     _container = builder.Build(); 
    } 
} 

重構test.cs中的鏈接

[TestFixture] 
public class Test 
{ 

    public class ExceptionFoo : IFoo 
    { 
     public void DoStuff() 
     { 
      throw new Exception(); 
     } 
    } 

    [Test] 
    public void ShouldReturn0WhenExceptionEncountered() 
    { 
     AutofacConfig.OverridenRegistrations = builder => 
     { 
      builder.RegisterType<ExceptionFoo>().AsImplementedInterfaces(); 
     }; 

     var result = Program.Main(); 

     Assert(0, result); 
    } 
} 

我們AutoFac配置由於封裝級別的不同,問題/答案看起來不同,所以這對我來說是有效的。

+0

我認爲僅在測試過程中添加功能纔是最好的選擇。 – kiziu

+0

這看起來不太好,因爲我們必須修改要用於單元測試的代碼,而且我們仍然依賴單元測試中的IoC –

+0

您是否有其他建議?我很樂意聽到其他的可能性:)隨時回答! – Kritner