簡體   English   中英

JustMock - 檢查傳遞的方法參數的值

[英]JustMock - check value of passed method argument

我使用JustMock框架並具有以下斷言:

Mock.Assert(() => activityListenerMock.PeriodPassed(
  Arg.Matches<Period>(e => e.Length == expectedLength)));

它失敗了,含有神秘的信息:

Occurrence expectation failed. Expected at least 1 call. Calls so far: 0

我怎樣才能得到更好的信息。 我想知道它被稱為什么價值。

方法實際上被調用但是有錯誤的參數,因為當我將斷言更改為跟隨它傳遞時:

Mock.Assert(() => activityListenerMock.PeriodPassed(
  Arg.IsAny<Period>()));

查看傳遞給PeriodPassed參數的一種方法是使用JustMock的DebugView

放置DebugView.IsTraceEnabled = true; 在測試開始時將DebugView.CurrentState添加到手表中。 接近最后,你會看到一些調整: Invocations: (ByRef ...).PeriodPassed("period value will go here") called 1 time; (signature: ...) Invocations: (ByRef ...).PeriodPassed("period value will go here") called 1 time; (signature: ...)

期間值將顯示在“調用”列表中。

另一種方法是將匹配器提取到一個單獨的lambda中並使用斷點: Predicate<Period> matcher = e => e.Length == expectedLength; Mock.Assert(() => activityListenerMock.PeriodPassed( Arg.Matches<Period>(e => matcher(e)))); Predicate<Period> matcher = e => e.Length == expectedLength; Mock.Assert(() => activityListenerMock.PeriodPassed( Arg.Matches<Period>(e => matcher(e))));

現在,您可以在謂詞中放置斷點並檢查e參數的值。 這是有效的,因為現在謂詞不是表達式而是實際函數,所以現在你可以調試它。

就像Stefan Dragnev寫的那樣。 我使用他的想法,然后添加邏輯來驗證輸入。 如果不是預期值,則調用Assert.Fail()。 不確定是否有更好的方法,但這有效:

Mock.Arrange(() => _uowMock.Class.Add(
    Arg.Matches<ModelClass>(x => (CheckArgs(x, updated)))))
    .DoNothing().Occurs(3);

....

protected static bool CheckArgs(ModelClass x, int y)
{
    if (x.val != y)
    {
        Assert.Fail("Houston we have a problem");
    }

    return true;
}

添加額外的安排之前也為我工作,但它是非常hacky:

Mock.Arrange(() => activityListenerMock.PeriodPassed(Arg.IsAny<Period>())).
  DoInstead((Period p) => Console.WriteLine("Actual " + p.Length+" expected "+expectedLength));

今天陷入同樣的​​困境,並開始擴展Krzysztof的想法,擴展一些。 它雖然粗糙但功能齊全。

public static class JustMockExtensions {
        public static FuncExpectation<T> PrintParams<T, T1>(this FuncExpectation<T> mock) {
            return mock.DoInstead<T1, T>((arg1, arg2) => {
                string message = string.Empty;
                message += Process(arg1);
                message += Process(arg2);
                Console.WriteLine(message);
            });
        }

        private static string Process<T>(T obj) {
            if (typeof(T).IsEnum) {
                return Enum.GetName(typeof(T), obj);
            }
            return obj.ToString();
        }
    }

到目前為止,以這種方式使用它允許它在正常流程中進行管道傳輸。

Mock.Arrange(() => foo.bar(Arg.IsAny<Widget>(), Arg.IsAny<WidgetTypeEnum>()))
                .PrintParams<Widget, WidgetTypeEnum>()
                .MustBeCalled();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM