Verify a method call happening in a separate thread/thread pool using MoqHow do I use reflection to call a generic method?Using Moq to determine if a method is calledHow to verify that method was NOT called in Moq?Verifying a method was calledVerifying a specific parameter with MoqHow do I verify a method was called?Verify a method call using MoqHow to call asynchronous method from synchronous method in C#?Moq - verifying a call with parameter that is changed during the execution of the testIf we don't verify that private methods are called with unit tests, how do we verify that they are called?

Did Wernher von Braun really have a "Saturn V painted as the V2"?

Best model for precedence constraints within scheduling problem

Just one file echoed from an array of files

Is "stainless" a bulk or a surface property of stainless steel?

Tabularx with hline and overrightarrow vertical spacing

Outer Class can have how many inner class(es)

Adding things to bunches of things vs multiplication

What was the intention with the Commodore 128?

Why don't politicians push for fossil fuel reduction by pointing out their scarcity?

Is there a commercial liquid with refractive index greater than n=2?

Reducing contention in thread-safe LruCache

Atmospheric methane to carbon

Sinc interpolation in spatial domain

What allows us to use imaginary numbers?

Would getting a natural 20 with a penalty still count as a critical hit?

9 hrs long transit in DEL

Vegetarian dishes on Russian trains (European part)

What's the point of writing that I know will never be used or read?

What does a comma signify in inorganic chemistry?

Meaning and structure of headline "Hair it is: A List of ..."

Postdoc interview - somewhat positive reply but no news?

What exactly happened to the 18 crew members who were reported as "missing" in "Q Who"?

Is it alright to say good afternoon Sirs and Madams in a panel interview?

Playing a fast but quiet Alberti bass



Verify a method call happening in a separate thread/thread pool using Moq


How do I use reflection to call a generic method?Using Moq to determine if a method is calledHow to verify that method was NOT called in Moq?Verifying a method was calledVerifying a specific parameter with MoqHow do I verify a method was called?Verify a method call using MoqHow to call asynchronous method from synchronous method in C#?Moq - verifying a call with parameter that is changed during the execution of the testIf we don't verify that private methods are called with unit tests, how do we verify that they are called?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have successfully setup and verified methods with Moq before but somehow I can't get this to work. I tried various answers on the same exception without luck.



I have implemented observer pattern, so I'm mocking IObserver<T>:



var mock = new Mock<IObserver<T>>();
mock.Setup(s => s.OnCompleted());


Here the OnCompleted() looks something like



public void OnCompleted()




Now in the test, using the mock, I do like this:



// observable is the SUT.
var unsubscriber = observable.Subscribe(mock.Object);
// Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
unsubscriber.Dispose();


I get the following error:



Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: v => v.OnCompleted()

Configured setups:
IObserver<T> s => s.OnCompleted()
No invocations performed.


EDIT: SUT Code



SUT is a class initialized a using a factory method. I will summarize the relevant parts here:



There's an initializer method:



public void InitializeMyClass()

for(var i = 0; i < threads.Count; i++)

Task.Factory.StartNew(() => Proc())


this.timer = new Timer(CheckStatus, null, 0, 1000);



CheckStatus method checks if the workloads in threads started in Initializer reaches a specific status and raises the event indicating completion:



private void CheckStatus(object status)

// Inspect all background threads.
// This is simply done by observing a set of values in a concurrent dict<int, bool>.:

if (!this.concurrentDict.Values.Any(a => a))

this.NotifyObservers();
this.timer.Change(Timeout.Infinite, Timeout.Infinite);




NotifyObservers() calls the OnCompleted() method:



private void NotifyObservers()

foreach(o in observers)

o.OnCompleted();











share|improve this question





















  • 1





    Your verify would fail since that OnCompleted() would never get called in test scenario

    – Rahul
    Mar 27 at 9:58






  • 1





    @swdon try setup it with callback like mock.Setup(...).Callback(() => put breakpoint here) and you will see did it actually called

    – Aleks Andreev
    Mar 27 at 10:14






  • 2





    Could you share the sut code?

    – Johnny
    Mar 27 at 11:12






  • 1





    @swdon While the added code snippets shed some light on the problem you need to provide a minimal reproducible example that can be used to reproduce the problem. Otherwise we are left guess what other code that may have been omitted might be causing problems.

    – Nkosi
    Mar 27 at 13:48






  • 1





    @swdon here is suggestion. Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.

    – Nkosi
    Mar 27 at 14:02


















2















I have successfully setup and verified methods with Moq before but somehow I can't get this to work. I tried various answers on the same exception without luck.



I have implemented observer pattern, so I'm mocking IObserver<T>:



var mock = new Mock<IObserver<T>>();
mock.Setup(s => s.OnCompleted());


Here the OnCompleted() looks something like



public void OnCompleted()




Now in the test, using the mock, I do like this:



// observable is the SUT.
var unsubscriber = observable.Subscribe(mock.Object);
// Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
unsubscriber.Dispose();


I get the following error:



Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: v => v.OnCompleted()

Configured setups:
IObserver<T> s => s.OnCompleted()
No invocations performed.


EDIT: SUT Code



SUT is a class initialized a using a factory method. I will summarize the relevant parts here:



There's an initializer method:



public void InitializeMyClass()

for(var i = 0; i < threads.Count; i++)

Task.Factory.StartNew(() => Proc())


this.timer = new Timer(CheckStatus, null, 0, 1000);



CheckStatus method checks if the workloads in threads started in Initializer reaches a specific status and raises the event indicating completion:



private void CheckStatus(object status)

// Inspect all background threads.
// This is simply done by observing a set of values in a concurrent dict<int, bool>.:

if (!this.concurrentDict.Values.Any(a => a))

this.NotifyObservers();
this.timer.Change(Timeout.Infinite, Timeout.Infinite);




NotifyObservers() calls the OnCompleted() method:



private void NotifyObservers()

foreach(o in observers)

o.OnCompleted();











share|improve this question





















  • 1





    Your verify would fail since that OnCompleted() would never get called in test scenario

    – Rahul
    Mar 27 at 9:58






  • 1





    @swdon try setup it with callback like mock.Setup(...).Callback(() => put breakpoint here) and you will see did it actually called

    – Aleks Andreev
    Mar 27 at 10:14






  • 2





    Could you share the sut code?

    – Johnny
    Mar 27 at 11:12






  • 1





    @swdon While the added code snippets shed some light on the problem you need to provide a minimal reproducible example that can be used to reproduce the problem. Otherwise we are left guess what other code that may have been omitted might be causing problems.

    – Nkosi
    Mar 27 at 13:48






  • 1





    @swdon here is suggestion. Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.

    – Nkosi
    Mar 27 at 14:02














2












2








2


1






I have successfully setup and verified methods with Moq before but somehow I can't get this to work. I tried various answers on the same exception without luck.



I have implemented observer pattern, so I'm mocking IObserver<T>:



var mock = new Mock<IObserver<T>>();
mock.Setup(s => s.OnCompleted());


Here the OnCompleted() looks something like



public void OnCompleted()




Now in the test, using the mock, I do like this:



// observable is the SUT.
var unsubscriber = observable.Subscribe(mock.Object);
// Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
unsubscriber.Dispose();


I get the following error:



Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: v => v.OnCompleted()

Configured setups:
IObserver<T> s => s.OnCompleted()
No invocations performed.


EDIT: SUT Code



SUT is a class initialized a using a factory method. I will summarize the relevant parts here:



There's an initializer method:



public void InitializeMyClass()

for(var i = 0; i < threads.Count; i++)

Task.Factory.StartNew(() => Proc())


this.timer = new Timer(CheckStatus, null, 0, 1000);



CheckStatus method checks if the workloads in threads started in Initializer reaches a specific status and raises the event indicating completion:



private void CheckStatus(object status)

// Inspect all background threads.
// This is simply done by observing a set of values in a concurrent dict<int, bool>.:

if (!this.concurrentDict.Values.Any(a => a))

this.NotifyObservers();
this.timer.Change(Timeout.Infinite, Timeout.Infinite);




NotifyObservers() calls the OnCompleted() method:



private void NotifyObservers()

foreach(o in observers)

o.OnCompleted();











share|improve this question
















I have successfully setup and verified methods with Moq before but somehow I can't get this to work. I tried various answers on the same exception without luck.



I have implemented observer pattern, so I'm mocking IObserver<T>:



var mock = new Mock<IObserver<T>>();
mock.Setup(s => s.OnCompleted());


Here the OnCompleted() looks something like



public void OnCompleted()




Now in the test, using the mock, I do like this:



// observable is the SUT.
var unsubscriber = observable.Subscribe(mock.Object);
// Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
unsubscriber.Dispose();


I get the following error:



Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: v => v.OnCompleted()

Configured setups:
IObserver<T> s => s.OnCompleted()
No invocations performed.


EDIT: SUT Code



SUT is a class initialized a using a factory method. I will summarize the relevant parts here:



There's an initializer method:



public void InitializeMyClass()

for(var i = 0; i < threads.Count; i++)

Task.Factory.StartNew(() => Proc())


this.timer = new Timer(CheckStatus, null, 0, 1000);



CheckStatus method checks if the workloads in threads started in Initializer reaches a specific status and raises the event indicating completion:



private void CheckStatus(object status)

// Inspect all background threads.
// This is simply done by observing a set of values in a concurrent dict<int, bool>.:

if (!this.concurrentDict.Values.Any(a => a))

this.NotifyObservers();
this.timer.Change(Timeout.Infinite, Timeout.Infinite);




NotifyObservers() calls the OnCompleted() method:



private void NotifyObservers()

foreach(o in observers)

o.OnCompleted();








c# moq






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 1:30







swdon

















asked Mar 27 at 9:51









swdonswdon

1,5631 gold badge13 silver badges38 bronze badges




1,5631 gold badge13 silver badges38 bronze badges










  • 1





    Your verify would fail since that OnCompleted() would never get called in test scenario

    – Rahul
    Mar 27 at 9:58






  • 1





    @swdon try setup it with callback like mock.Setup(...).Callback(() => put breakpoint here) and you will see did it actually called

    – Aleks Andreev
    Mar 27 at 10:14






  • 2





    Could you share the sut code?

    – Johnny
    Mar 27 at 11:12






  • 1





    @swdon While the added code snippets shed some light on the problem you need to provide a minimal reproducible example that can be used to reproduce the problem. Otherwise we are left guess what other code that may have been omitted might be causing problems.

    – Nkosi
    Mar 27 at 13:48






  • 1





    @swdon here is suggestion. Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.

    – Nkosi
    Mar 27 at 14:02













  • 1





    Your verify would fail since that OnCompleted() would never get called in test scenario

    – Rahul
    Mar 27 at 9:58






  • 1





    @swdon try setup it with callback like mock.Setup(...).Callback(() => put breakpoint here) and you will see did it actually called

    – Aleks Andreev
    Mar 27 at 10:14






  • 2





    Could you share the sut code?

    – Johnny
    Mar 27 at 11:12






  • 1





    @swdon While the added code snippets shed some light on the problem you need to provide a minimal reproducible example that can be used to reproduce the problem. Otherwise we are left guess what other code that may have been omitted might be causing problems.

    – Nkosi
    Mar 27 at 13:48






  • 1





    @swdon here is suggestion. Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.

    – Nkosi
    Mar 27 at 14:02








1




1





Your verify would fail since that OnCompleted() would never get called in test scenario

– Rahul
Mar 27 at 9:58





Your verify would fail since that OnCompleted() would never get called in test scenario

– Rahul
Mar 27 at 9:58




1




1





@swdon try setup it with callback like mock.Setup(...).Callback(() => put breakpoint here) and you will see did it actually called

– Aleks Andreev
Mar 27 at 10:14





@swdon try setup it with callback like mock.Setup(...).Callback(() => put breakpoint here) and you will see did it actually called

– Aleks Andreev
Mar 27 at 10:14




2




2





Could you share the sut code?

– Johnny
Mar 27 at 11:12





Could you share the sut code?

– Johnny
Mar 27 at 11:12




1




1





@swdon While the added code snippets shed some light on the problem you need to provide a minimal reproducible example that can be used to reproduce the problem. Otherwise we are left guess what other code that may have been omitted might be causing problems.

– Nkosi
Mar 27 at 13:48





@swdon While the added code snippets shed some light on the problem you need to provide a minimal reproducible example that can be used to reproduce the problem. Otherwise we are left guess what other code that may have been omitted might be causing problems.

– Nkosi
Mar 27 at 13:48




1




1





@swdon here is suggestion. Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.

– Nkosi
Mar 27 at 14:02






@swdon here is suggestion. Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.

– Nkosi
Mar 27 at 14:02













1 Answer
1






active

oldest

votes


















3














This could be a threading issue or the timer might not have invoked by the time the verification was done. Which means that the mock members were not actually called yet when Verify was invoked.



You might have to wait a bit before verifying method call.



Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.



//Arrange

//...

//Act
// observable is the SUT.
var unsubscriber = observable.Subscribe(mock.Object);
// Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

await Task.Delay(TimeSpan.FromSeconds(1.5)); //Or some known duration

//Assert
mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
unsubscriber.Dispose();





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55374225%2fverify-a-method-call-happening-in-a-separate-thread-thread-pool-using-moq%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    This could be a threading issue or the timer might not have invoked by the time the verification was done. Which means that the mock members were not actually called yet when Verify was invoked.



    You might have to wait a bit before verifying method call.



    Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.



    //Arrange

    //...

    //Act
    // observable is the SUT.
    var unsubscriber = observable.Subscribe(mock.Object);
    // Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

    await Task.Delay(TimeSpan.FromSeconds(1.5)); //Or some known duration

    //Assert
    mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
    unsubscriber.Dispose();





    share|improve this answer





























      3














      This could be a threading issue or the timer might not have invoked by the time the verification was done. Which means that the mock members were not actually called yet when Verify was invoked.



      You might have to wait a bit before verifying method call.



      Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.



      //Arrange

      //...

      //Act
      // observable is the SUT.
      var unsubscriber = observable.Subscribe(mock.Object);
      // Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

      await Task.Delay(TimeSpan.FromSeconds(1.5)); //Or some known duration

      //Assert
      mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
      unsubscriber.Dispose();





      share|improve this answer



























        3












        3








        3







        This could be a threading issue or the timer might not have invoked by the time the verification was done. Which means that the mock members were not actually called yet when Verify was invoked.



        You might have to wait a bit before verifying method call.



        Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.



        //Arrange

        //...

        //Act
        // observable is the SUT.
        var unsubscriber = observable.Subscribe(mock.Object);
        // Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

        await Task.Delay(TimeSpan.FromSeconds(1.5)); //Or some known duration

        //Assert
        mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
        unsubscriber.Dispose();





        share|improve this answer













        This could be a threading issue or the timer might not have invoked by the time the verification was done. Which means that the mock members were not actually called yet when Verify was invoked.



        You might have to wait a bit before verifying method call.



        Try adding a delay between the Act and Assertion in the test to give the timer enough time to do its thing.



        //Arrange

        //...

        //Act
        // observable is the SUT.
        var unsubscriber = observable.Subscribe(mock.Object);
        // Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

        await Task.Delay(TimeSpan.FromSeconds(1.5)); //Or some known duration

        //Assert
        mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
        unsubscriber.Dispose();






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 28 at 1:33









        NkosiNkosi

        133k22 gold badges170 silver badges234 bronze badges




        133k22 gold badges170 silver badges234 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55374225%2fverify-a-method-call-happening-in-a-separate-thread-thread-pool-using-moq%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현