2012-11-22 127 views
1

我使用的是Machine.Fakes.NSubstitute,並且想要「僞造」返回值,以便如果輸入參數匹配特定值,則返回模擬對象,否則返回null。爲什麼這個Machine.Fakes參數匹配會拋出異常?

我試過如下:

host.WhenToldTo(h => h.GetTenantInstance(Param.Is(new Uri("http://foo.bar")))) 
    .Return(new TenantInstance()); 

但它拋出以下異常:

System.InvalidCastException:無法投類型 'System.Linq.Expressions.NewExpression' 的對象鍵入 'System.Linq.Expressions.ConstantExpression'。

我目前的解決辦法是做到以下幾點:

host.WhenToldTo(h => h.GetTenantInstance(Param.IsAny<Uri>())) 
    .Return<Uri>(uri => uri.Host == "foo.bar" ? new TenantInstance() : null); 

這是一個有點臭。

回答

3

我在這裏看到三個方面:

  1. 當引用類型返回值的方法被稱爲模仿的對象上,並沒有行爲已設立電話,模擬對象將返回模擬。如果您希望它返回null,您必須明確配置它。因此,它是不夠的,建立

    host.WhenToldTo(h => h.GetTenantInstance(Param.Is(new Uri("http://foo.bar")))) 
        .Return(new TenantInstance()); 
    

    您還可以設置其他情況下像這樣的東西:

    host.WhenToldTo(h => h.GetTenantInstance(Param<Uri>.Matches(x => !x.Equals(new Uri("http://foo.bar"))))) 
        .Return((TenantInstance)null); 
    

    我發現你「解決辦法」解決方案比這些更優雅兩個設置。

  2. 當您匹配等於的方法調用參數時,有無需使用Param.Is()。你可以簡單地設置了

    host.WhenToldTo(h => h.GetTenantInstance(new Uri("http://foo.bar"))) 
        .Return(new TenantInstance()); 
    
  3. 您在使用時Param.Is()這裏是缺點Machine.Fakes的得到一個異常的事實的行爲。我看不到爲什麼這不應該起作用。我會在某個時候糾正這一點,並讓你知道。
+1

該bug在版本1.0.4中修復。即使使用'Param.Is()'也不會發生異常。 –

相關問題