Skip to Content
C#并发编程经典实例(第2版)
book

C#并发编程经典实例(第2版)

by Stephen Cleary
November 2020
Intermediate to advanced
226 pages
5h 34m
Chinese
Posts & Telecom Press
Content preview from C#并发编程经典实例(第2版)
78
7
他们都害怕测试并发代码,而且普遍认为这难以实现。然而,就像本章示例所展示的那
样,对并发代码执行单元测试并没有想象中那么困难。现代化的功能和库,比如
async
System.Reactive
,已经对测试做了充分考量,且效果显著。可以参考本章示例编写单元测
试,这样做对并发方面的新手尤其有用。(对新手而言,并发代码看起来既复杂又可怕。)
7.1
 对
async
方法进行单元测试
问题
假设需要对某个
async
方法进行单元测试。
解决方案
大多数现代单元测试框架支持
async Task
单元测试方法,包括
MSTest
NUnit
xUnit
。从
Visual Studio 2012
起,
MSTest
开始支持这些测试,如果使用别的单元测试框架,那么需要
升级到最新版本。
以下示例展示了
async
MSTest
单元测试:
[TestMethod]
public async
Task MyMethodAsync_ReturnsFalse()
{
var
objectUnderTest = ...;
bool
result =
await
objectUnderTest.MyMethodAsync();
Assert.IsFalse(result);
}
单元测试框架会留意到方法的返回类型是
Task
,然后自动等待任务完成,并将测试标记为
“成功”或“失败”。
如果所采用的单元测试框架不支持
async Task
单元测试,则需要借助一些辅助操作,等待
被测试的异步操作。有一种选项是使用
GetAwaiter().GetResult() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

解密金融数据

解密金融数据

Justin Pauley
PHP编程:第4版

PHP编程:第4版

Kevin Tatroe, Peter MacIntyre

Publisher Resources

ISBN: 9787115550606