2012-10-26 108 views
1

我想在我的項目中嘲笑靜態函數。我無法使用Rhynomocks這樣做,因此試圖使用Typemock來模擬靜態函數。使用TypeMock嘲弄靜態函數

他們說,這是possbile使用typemock和相同的例子來模擬靜電功能提供了以下文章

http://www.typemock.com/basic-typemock-unit-testing

但似乎對我的工作不。下面是我的代碼:

公共類Class1Test
{
[隔離(設計= DesignMode.Pragmatic)
[測試]
公共void函數()
{ Isolate.Fake.StaticMethods (Members.MustSpecifyReturnValues);

 Isolate.WhenCalled(() => LoggerFactory.Add(6, 4)).WillReturn(11); 

     int value = LoggerFactory.Add(5, 6); 
    } 


} 

----------------------------------------- ------ LoggerFactory.cs

公共類的LoggerFactory {

public static int Add(int intx, int inty) 
    { 
     return intx + inty; 
    } 

} 

錯誤我得到的是:

*僞造非虛方法是不可能的InterfaceOnly設計模式。使用[Isolated(DesignMode.Pragmatic)]來僞造這個。在這裏瞭解更多http://www.typemock.com/isolator-design-mode

在此先感謝。

回答

0

您的示例代碼看起來不完整的。我只是稍微修改一下使用你的代碼的複製品,它工作正常。具體而言,Isolate.Fake.StaticMethods調用缺少您打算進行模擬的類型。

using System; 
using NUnit.Framework; 
using TypeMock.ArrangeActAssert; 

namespace TypeMockDemo 
{ 
    public class LoggerFactory 
    { 
    public static int Add(int intx, int inty) 
    { 
     return intx + inty; 
    } 
    } 

    // The question was missing the TestFixtureAttribute. 
    [TestFixture] 
    public class LoggerFactoryFixture 
    { 
    // You don't have to specify DesignMode.Pragmatic - that's the default. 
    [Isolated(Design = DesignMode.Pragmatic)] 
    [Test] 
    public void Add_CanMockReturnValue() 
    { 
     // The LoggerFactory type needs to be specified here. This appeared 
     // missing in the example from the question. 
     Isolate.Fake.StaticMethods<LoggerFactory>(Members.MustSpecifyReturnValues); 

     // The parameters in the Add call here are totally ignored. 
     // It's best to put "dummy" values unless you are using 
     // WithExactArguments. 
     Isolate.WhenCalled(() => LoggerFactory.Add(0, 0)).WillReturn(11); 

     // Note the parameters here. No WAY they add up to 11. That way 
     // we know you're really getting the mock value. 
     int value = LoggerFactory.Add(100, 200); 

     // This will pass. 
     Assert.AreEqual(11, value); 
    } 
    } 
} 

如果你能粘貼代碼到項目(與Typemock和NUnit的引用),它不工作,那麼你可能有執行測試的麻煩正確,或者你可能有你的機器上配置錯誤。無論哪種情況,如果上述代碼無效,您可能需要聯繫Typemock支持。

1

你爲什麼試圖在第一個地方模擬?你的方法不需要嘲諷,因爲它是無狀態的 - 只是直接測試:

[Test] 
public void Six_Plus_Five_Is_Eleven() 
{ 
    Assert.That(11, Is.EqualTo(LoggerFactory.Add(6, 5)); 
}