rspec/rules/S2925/vbnet/rule.adoc

63 lines
2.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2023-06-20 16:16:29 +02:00
Using `Thread.Sleep` in a test might introduce unpredictable and inconsistent results depending on the environment. Furthermore, it will block the https://en.wikipedia.org/wiki/Thread_(computing)[thread], which means the system resources are not being fully used.
[source,vbnet,diff-id=1,diff-type=noncompliant]
----
<TestMethod>
Public Sub SomeTest()
Threading.Thread.Sleep(500) ' Noncompliant
' assertions...
End Sub
----
An alternative is a task-based asynchronous approach, using https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/[async and await].
More specifically the https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.delay[Task.Delay] method should be used, because of the following advantages:
* It is **asynchronous**: The thread will not be blocked, but instead will be reused by other operations
* It is more **precise** in timing the delay than `Thread.Sleep`
2023-06-20 16:16:29 +02:00
* It can be **canceled and continued**, which gives more flexibility and control in the timing of your code
[source,vbnet,diff-id=1,diff-type=compliant]
----
<TestMethod>
Public Async Function SomeTest() As Task
Await Task.Delay(500)
' assertions...
End Function
----
Another scenario is when some data might need to be mocked using https://github.com/moq/moq4[Moq], and a delay needs to be introduced:
[source,vbnet,diff-id=2,diff-type=noncompliant]
----
<TestMethod>
Public Sub UserService_Test()
Dim UserService As New Mock(Of UserService)
Dim Expected As New User
UserService.Setup(Function(X) X.GetUserById(42)).Returns(
Function()
Threading.Thread.Sleep(500) ' Noncompliant
Return Task.FromResult(Expected)
End Function)
' assertions...
End Sub
----
An alternative to `Thread.Sleep` while mocking with `Moq` is to use `ReturnsAsync` and pass the amount of time to delay there:
[source,vbnet,diff-id=2,diff-type=compliant]
----
<TestMethod>
Public Sub UserService_Test()
Dim UserService As New Mock(Of UserService)
Dim Expected As New User
UserService.Setup(Function(X) X.GetUserById(42)).ReturnsAsync(Expected, TimeSpan.FromMilliseconds(500))
' assertions...
End Sub
----
include::../resources-dotnet.adoc[]
include::../rspecator-dotnet.adoc[]