. NET Unit Testing-Multithreading

Source: Internet
Author: User

Given the. NET Framework 4.5. NET adds support for async/await, the asynchronous content discussed in this article is based on async/await

?? Client-side interface development, multithreading is not a topic to escape, and multithreading is bound to the stability of the program to bring challenges, unit testing is more important. Multithreaded unit tests have more detail to note than tests that synchronize code.

Async void and Async Task.

?? If you have a bad luck one day, you need to add unit tests for a method similar to the following:

public static bool Changed;public static async void ChangeAsync(){    await Task.Run(() =>    {        Task.Delay(1000);        Changed = true;    });}

You find that there are some wonderful ways to test this method, such as:

[TestMethod()]public void ChangeAsyncTest_OriginalFalse_ChangeToTrue(){    AsyncClient.Changed = false;    AsyncClient.ChangeAsync();    Thread.Sleep(1100);    Assert.IsTrue(AsyncClient.Changed);}

Obviously, this delay wait is extremely disgusting, if the Changeasync method returns not void but task, we can await happily:

[TestMethod()]public async Task ChangeAsyncTest_OriginalFalse_ChangeToTrue(){    AsyncClient.Changed = false;    await AsyncClient.ChangeAsync();    Assert.IsTrue(AsyncClient.Changed);}

It is important to note that the task must also be returned in the Async unit test method, which is the MSTest convention, or the test method cannot be run. (In fact, MSTest also needs to use the returned task to collect the exception, see Async/await best practices for more content in this section)

Abandon ExpectedException

?? In testing whether the program throws an exception as expected, we often use expectedexception, this guy has a problem, it is the method body of the entire test method is captured, In other words, the non-action code in the test method throws an exception that can still be captured by ExpectedException, which creates a potential bug, and in order to solve this problem, it is often necessary to write some helper methods before MSTest V2, but MSTest V2 asserts that the Assert.throwsexceptionasync and Assert.throwsexception are added to the library to pinpoint exactly which code throws the exception. Let's say the code we're testing is similar to the following:

public static async Task ChangeAsync(){    await Task.Run(() =>    {        throw new InvalidOperationException();    });}

The test code can be written like this:

[TestMethod()]public async Task ChangeAsyncTest_ThrowInvalidOperationException(){    await Assert.ThrowsExceptionAsync<InvalidOperationException>(async () =>    {        await AsyncClient.ChangeAsync();    });}
Async method Mock

?? In MOQ, the mock of the Async method is also extremely simple, assuming that there is such an interface:

public interface ITextReader{    Task<string> ReadTextAsync();}

In the test code, the result of the mock return can be as follows two ways:

var mockTextReader = new Mock<ITextReader>();//可以这样mockTextReader.Setup(x => x.ReadTextAsync()).Returns(async ()=>await Task.FromResult("mockValue"));//也可以这样mockTextReader.Setup(x => x.ReadTextAsync()).ReturnsAsync(()=> "mockValue");

Date:2017-11-30 15:26:34

. NET Unit Testing-Multithreading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.