
When an include is not surrounded by empty lines, its content is inlined on the same line as the adjacent content. That can lead to broken tags and other display issues. This PR fixes all such includes and introduces a validation step that forbids introducing the same problem again.
63 lines
2.2 KiB
Plaintext
63 lines
2.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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`
|
|
* 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[] |