简体   繁体   中英

Moq Timeout Exception C#

I am using the Moq testing framework in C#, and I trying to create a unit test where I have a method which calls out to a service on a remote server over a unreliable network.

In side the method I am trying to unit test I have the following code:

    Task.Factory.StartNew(() => this.remoteClient.SomeMethod(userDetails)).Wait(Timespan.FromSeconds(10));

The aim of the unit test is to mock out the timeout where the service failed to respond within 10 seconds.

So far I have the unit test as follows, which does work, but I am feeling that it is not quite right.

   mockRemoteClientService.Setup(r =>r.SomeMethod(It.IsAny<string>())).Callback(() => Thread.Sleep(11000));

Can anyone advise me whether the approach I am taking is correct or is there another way to do this?

You can use a cancellation token to setup the actual timeout.

When you want to mock out the service call to simulate a timeout, you can use Throws (or ThrowsAsync in case of an async method) to throw a TaskCancelledException or TimeOutException like so:

mockRemoteClientService.Setup(x => x.SomeMethod(It.IsAny<string>())).Throw(new TaskCancelledException());

Then Assert that you handle the response correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM