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;
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
|
show 14 more comments
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
1
Your verify would fail since thatOnCompleted()
would never get called in test scenario
– Rahul
Mar 27 at 9:58
1
@swdon try setup it with callback likemock.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
|
show 14 more comments
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
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
c# moq
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 thatOnCompleted()
would never get called in test scenario
– Rahul
Mar 27 at 9:58
1
@swdon try setup it with callback likemock.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
|
show 14 more comments
1
Your verify would fail since thatOnCompleted()
would never get called in test scenario
– Rahul
Mar 27 at 9:58
1
@swdon try setup it with callback likemock.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
|
show 14 more comments
1 Answer
1
active
oldest
votes
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();
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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();
add a comment |
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();
add a comment |
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();
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();
answered Mar 28 at 1:33
NkosiNkosi
133k22 gold badges170 silver badges234 bronze badges
133k22 gold badges170 silver badges234 bronze badges
add a comment |
add a comment |
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.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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