2013-07-08 22 views
4

我正在使用Rhino Mocks 3.5來模擬一個需要2個參數的服務方法調用,並且我想確保正確設置對象上的propery。Rhino模擬參數檢測...有更好的方法嗎?

// Method being tested 
void UpdateDelivery(Trade trade) 
{ 
    trade.Delivery = new DateTime(2013, 7, 4); 
    m_Service.UpdateTrade(trade, m_Token); // mocking this 
} 

這裏是我的代碼(工作)

service, trade, token declared/new'd up ... etc. 
... 

using (m_Mocks.Record()) 
{ 
    Action<Trade, Token> onCalled = (tradeParam, tokenParam) => 
      { 
       // Inspect/verify that Delivery prop is set correctly 
       // when UpdateTrade called 
       Assert.AreEqual(new DateTime(2013, 7, 4), tradeParam.Delivery);      
      }; 

    Expect.Call(() => m_Service.UpdateTrade(Arg<Trade>.Is.Equal(trade), Arg<Token>.Is.Equal(token))).Do(onCalled); 
} 

using (m_Mocks.Playback()) 
{ 
    m_Adjuster = new Adjuster(service, token); 
    m_Adjuster.UpdateDelivery(trade); 
} 

是否還有更好的,更簡潔,straightfoward測試這個使用犀牛製品的方法的一部分?我已經看過使用Contraints的帖子,但我不喜歡用字符串名稱來識別屬性/值。

回答

5

你可以做到以下幾點:

Expect.Call(() => m_Service.UpdateTrade(
    Arg<Trade>.Matches(t => t.Delivery.Equals(new DateTime(2013, 7, 3))), 
    Arg<Token>.Is.Anything) 
); 

也請注意,如果你不打算驗證token參數在這個測試中,那麼你可以使用Is.Anything約束它。


注:

RhinoMocks 3.5和.NET4 +使用Matches(Expression<Predicate<..>>)過載時拋出AmbiguousMatchException。如果這是不可能更新到RhinoMocks 3.6(有原因),人們仍然可以使用Matches(AbstractConstraint)超載像這樣:

Arg<Trade>.Matches(
    Property.Value("Delivery", new DateTime(2013, 7, 3))) 

或:

Arg<Trade>.Matches(
    new PredicateConstraint<DateTime>(
    t => t.Delivery.Equals(new DateTime(2013, 7, 3)))) 
+1

感謝亞歷山大。這正是我所期待的。我收到「System.Reflection.AmbiguousMatchException:找到了不明確的匹配項。」當我跑步時。我正在使用.Net 4.0 – KornMuffin

+0

你得到這個異常的方法是什麼? –

+0

當在被測試的類中調用m_Service.UpdateTrade方法時,由Rhino Mocks引發。 System.Reflection.AmbiguousMatchException:找到不明確的匹配項。 \t在System.RuntimeType.GetMethodImpl(字符串名稱,的BindingFlags bindingAttr,粘結劑粘結劑,CallingConventions callConv,類型[]類型,ParameterModifier []改性劑) \t在System.Type.GetMethod(字符串名稱) \t在Rhino.Mocks。 Constraints.LambdaConstraint.Eval(對象OBJ) \t在Rhino.Mocks.Expectations.ConstraintsExpectation.DoIsExpected(對象[]參數) \t在Rhino.Mocks.Expectations.AbstractExpectation.IsExpected(對象[]參數)... – KornMuffin

相關問題