当前位置: 首页 > 编程日记 > 正文

rxswift中hud_如何在RxSwift中运行测试

rxswift中hud

by Navdeep Singh

通过Navdeep Singh

如何在RxSwift中运行测试 (How to run tests in RxSwift)

RxTest and RxBlocking are part of the RxSwift repository. They are made available via separate pods, however, and so require separate imports.

RxTestRxBlocking是RxSwift存储库的一部分。 但是,它们是通过单独的容器提供的,因此需要单独导入。

RxTest provides useful additions for testing Rx code. It includes TestScheduler, which is a virtual time scheduler, and provides methods for adding events at precise time intervals.

RxTest为测试Rx代码提供了有用的补充。 它包括TestScheduler (这是一个虚拟的时间计划程序),并提供了以精确的时间间隔添加事件的方法。

RxBlocking, on the other hand, enables you to convert a regular Observable sequence to a blocking observable, which blocks the thread it’s running on until the observable sequence completes or a specified timeout is reached. This makes testing asynchronous operations much easier.

另一方面, RxBlocking使您可以将常规的Observable序列转换为阻塞的Observable,这将阻塞正在运行的线程,直到Observable序列完成或达到指定的超时为止。 这使测试异步操作变得更加容易。

Let’s look at each one now.

让我们现在看看每个。

接收测试 (RxTest)

As described above, RxTest is part of the same repository as RxSwift. There is one more thing to know about RxTest before we dive into some RxTesting: RxTest exposes two types of Observables for testing purposes.

如上所述, RxTest与RxSwift是同一存储库的一部分。深入研究RxTesting之前,还需要了解有关RxTest的另一件事:RxTest出于测试目的公开了两种类型的Observable。

  • HotObservables

    热点观察
  • ColdObservables

    冷观测

HotObservables replay events at specified times using a test scheduler, regardless of whether there are any subscribers.

HotObservables使用测试计划程序在指定的时间重放事件,而不管是否有订阅者。

ColdObservables work more like regular Observables, replaying their elements to their new subscribers upon subscription.

ColdObservables的工作方式与常规Observables相似,在订阅时将其元素重播给新订阅者。

Rx阻止 (RxBlocking)

If you are familiar with expectations in XCTest, you will know that it’s another way to test asynchronous operations. Using RxBlocking just happens to be way easier. Let’s start with a small implementation so we can see how to take advantage of this library while testing asynchronous operations.

如果您熟悉XCTest中的期望,您将知道这是测试异步操作的另一种方法。 使用RxBlocking只是更容易。 让我们从一个小的实现开始,以便我们可以看到在测试异步操作时如何利用该库。

使用RxBlocking进行测试 (Testing with RxBlocking)

We will start a new test and create an Observable of 10, 20, and 30, as follows:

我们将开始一个新的测试,并创建一个10、20和30的Observable,如下所示:

func testBlocking(){        let observableToTest = Observable.of(10, 20, 30)    }

Now we will define the result as equal to calling toBlocking() on the observable we created:

现在,我们将定义的结果等于在我们创建的可观察对象上调用toBlocking():

let result = observableToTest.toBlocking()

toBlocking() returns a blocking Observable to a straight array, as you can see here:

toBlocking()将阻塞的Observable返回到直线数组,如您在此处看到的:

We will need to use the first method if we want to discover which is a throwing method. So we will wrap it in a do catch statement, and then we will add an AssertEquals statement if it is successful, as follows:

如果要发现哪种方法是投掷方法,则需要使用第一种方法。 因此,我们将其包装在do catch语句中,然后,如果成功,则将添加AssertEquals语句,如下所示:

func testBlocking(){        let observableToTest = Observable.of(10, 20, 30)        do{            let result = try observableToTest.toBlocking().first()            XCTAssertEqual(result, 10)        } catch {        }    }

Alternatively, an Assert fails if it’s not this:

或者,如果不是,则断言失败:

do{            let result = try observableToTest.toBlocking().first()            XCTAssertEqual(result, 10)        } catch {            XCTFail(error.localizedDescription)        }

That’s it! Let’s run the test, and you will see that the test passes. We can simplify this test with just two lines of code by forcing the try.

而已! 让我们运行测试,您将看到测试通过。 通过强制尝试,我们可以仅用两行代码来简化此测试。

Again, this is more acceptable on test than production code. We will comment out the do catch statement and then write the assert equals in a single line, as follows:

同样,在测试中这比生产代码更可接受。 我们将注释掉do catch语句,然后在一行中编写断言等于,如下所示:

XCTAssertEqual(try! observableToTest.toBlocking().first(), 10)

Rerun the test, and you will see that the test passes once again. The overall code with comments looks like this:

重新运行测试,您将看到测试再次通过。 带有注释的整体代码如下所示:

func testBlocking(){        let observableToTest = Observable.of(10, 20, 30)//        do{//            let result = try observableToTest.toBlocking().first()//            XCTAssertEqual(result, 10)//        } catch {//            XCTFail(error.localizedDescription)//        }        XCTAssertEqual(try! observableToTest.toBlocking().first(), 10)    }

How’s that for succinct? Truth be told, that Observable sequence would actually be synchronous already if we printed emitted elements in a subscription to it followed by a marker. The marker will be printed after the subscription’s completed event.

那个怎么样? 实话实说,如果我们在订阅中先打印发出的元素,再加上标记,那么Observable序列实际上实际上已经是同步的。 订阅完成事件后,将打印标记。

To test an actual asynchronous operation, we will write one more test. This time, we will use a concurrent scheduler on a background thread, as follows:

为了测试实际的异步操作,我们将再编写一个测试。 这次,我们将在后台线程上使用并发调度程序,如下所示:

func testAsynchronousToArry(){        let scheduler = ConcurrentDispatchQueueScheduler(qos: .background)    }

Now, we will create an Observable of the simple sequence of integers. We will use map to double each value, as follows:

现在,我们将创建一个简单的整数序列的Observable。 我们将使用map将每个值加倍,如下所示:

let intObservbale = Observable.of(10, 20, 30)            .map{ $0 * 2 }

Then, we will subscribe on the scheduler:

然后,我们将订阅调度程序:

let intObservbale = Observable.of(10, 20, 30)            .map{ $0 * 2 }            .subscribeOn(scheduler)

Now we will write a do catch statement that is similar to the last test and calls toBlocking on the Observable, which should be observed on the main scheduler, as follows:

现在,我们将编写一个与上一个测试类似的do catch语句,并在Observable上调用toBlocking,应在主调度程序上对其进行观察,如下所示:

do{   let result = try intObservbale.observeOn(MainScheduler.instance).toBlocking().toArray()   } catch {   }

Then, we will add the same assertions as the previous example:

然后,我们将添加与先前示例相同的断言:

do{   let result = try intObservbale.observeOn(MainScheduler.instance).toBlocking().toArray()            XCTAssertEqual(result, [20, 40, 60])        } catch {            XCTFail(error.localizedDescription)        }

Now we will run the test, and you will note that it passes with the green check mark in the gutter.

现在,我们将运行测试,您会注意到它通过了带有槽中绿色复选标记的测试。

Note that the marker is printed before the emitted elements in the console, as shown:

请注意,标记在控制台中发出的元素之前打印,如下所示:

This is because these operations were executed asynchronously.

这是因为这些操作是异步执行的。

For other updates you can follow me on Twitter on my twitter handle @NavRudraSambyal

对于其他更新,您可以在我的Twitter句柄@NavRudraSambyal的Twitter上关注我。

To work with examples of hot and cold observables, you can find the link to my book Reactive programming in Swift 4

要处理冷热观测的示例,可以找到我的书《 Swift 4中的React式编程》的链接。

Thanks for reading, please share it if you found it useful :)

感谢您的阅读,如果您觉得有用,请分享:)

翻译自: https://www.freecodecamp.org/news/testing-in-rxswift-2b6eeaeaf432/

rxswift中hud

相关文章:

安装完DevExpress14.2.5,如何破解它呢?

DevExpress是一个界面控件套件,提供了一系列的界面控件套件的DotNet界面控件。DevExpress开发的控件有很强的实力,不仅功能丰富,应用简单,而且界面华丽,更可方便订制,方便开发人员开发。 下面介绍DevExpres…

Extjs Ext.TreePanel

TreePanel 简单实例。 <link rel"stylesheet" href"Js/ext-4.2/resources/css/ext-all-neptune.css"/><script src"Js/jQuery/jquery-1.8.2.min.js" type"text/javascript"></script><script src"Js/ext-…

php模糊搜索功能

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 前端 前端post请求并发送str参数>搜索的内容&#xff1b; PHP <?phpheader("Content-Type:text/html;charsetutf8"); header("Access-Control-Allow-Origin…

react 快速上手开发_React中测试驱动开发的快速指南

react 快速上手开发by Michał Baranowski通过MichałBaranowski React中测试驱动开发的快速指南 (A quick guide to test-driven development in React) Following the principles of Test-Driven Development (TDD) when writing a front-end React app might seem more dif…

iOS 相册和网络图片的存取

iOS 相册和网络图片的存取 保存 UIImage 到相册 UIKit UIKit 中一个古老的方法&#xff0c;Objective-C 的形式 void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo); 保存完成后&#xff0c;会调用 comple…

微信小程序实时聊天之WebSocket

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 1.所有监听事件先在onload监听。 // pages/index/to_news/to_news.js var app getApp(); var socketOpen false; var SocketTask false; var url ws://192.168.0.120:7011; Page…

webform repeater

repeater:由模板构成&#xff0c;解析后模板就不存在了 需要指定数据源进行数据绑定 List<Fruit> list new FruitDA().Select(); // 数据查询 &#xff08;随便查寻的&#xff09; Repeater1.DataSource list; // 赋值 Repeater1…

远程协助软件开发_这是我从事远程软件开发人员工作的主要技巧

远程协助软件开发by Colin Morgan通过科林摩根(Colin Morgan) 这是我从事远程软件开发人员工作的主要技巧 (Here are the top tips I’ve used to land a remote software developer job) Applying for a remote software developer job means you are voluntarily choosing t…

简谈-Python一些常用的爬虫技巧

第一种&#xff1a;基本的网页抓取 get方法 import urllib2url "链接response urllib2.urlopen(url)print response.read() post方法 import urllibimport urllib2url "链接form {name:abc,password:1234}form_data urllib.urlencode(form)request urllib2.Req…

微信小程序画布圆形进度条demo

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; wxml <!--pages/test/test.wxml--> <canvas style"width: 300px; height: 200px;" canvas-id"canvasid"></canvas>js // pages/test/test.js …

smarty 模板引擎

http://blog.csdn.net/zuiaituantuan/article/details/5951242 http://wenku.baidu.com/link?url-UHlSnTXOOAjFG1KjX6T9sEG6V4hNAMfRDpMuRRnc_FKbFAxiE5Ntk4lzxSm-7Z531uWdfvgYx81sdC61SgTZm7q8FdUt3gSs7ZlC0JR1SW转载于:https://www.cnblogs.com/hxjbc/p/4441879.html

flask url构建_如何为生产构建构建Flask-RESTPlus Web服务

flask url构建by Greg Obinna由格雷格奥比纳(Greg Obinna) 如何为生产构建构建Flask-RESTPlus Web服务 (How to structure a Flask-RESTPlus web service for production builds) In this guide I’ll show you a step by step approach for structuring a Flask RESTPlus web…

【2017-4-26】Winform 公共控件 菜单和工具栏

作废 等待重写 名称 功能取值赋值备注Button按钮多用来触发点击事件 CheckBox多选按钮 CheckedListBox多选按钮组 ComboBox下拉列表 DateTimePicker指定的格式选择时间日期 Lable说明性文字控件 LinkLable超链接类型文件控件 ListBox用户选择项 ListVie…

微信小程序限制当前位置和目的地的距离

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 1。获取当前位置经纬度 onLoad: function (options) {var that this;campaign_id campaign_idwx.getLocation({type: wgs84,success: function (res) {console.log(res)lat1 res.l…

命令行的全文搜索工具--ack

想必大家在命令行环境下工作时候&#xff0c;一定有想要查找当前目录下的源代码文件中的某些字符的需求&#xff0c;这时候如果使用传统方案&#xff0c;你可能需要输入一长串的命令&#xff0c;比如这样&#xff1a; 1. grep -R string dir/ 或者 grep -r -e string direct…

ecmascript_TC39及其对ECMAScript的贡献

ecmascriptby Parth Shandilya通过Parth Shandilya TC39及其对ECMAScript的贡献 (TC39 and its contributions to ECMAScript) Many people get confused about what is JavaScript and what is ECMAScript. Sometimes it’s hard to tell how they are connected with each o…

Winio驱动在64位windows下无法使用的解决方法

C#在使用WinIo的驱动开发类似按键精灵一类工具的时候&#xff0c;需要对相关的驱动进行注册才能正常启动&#xff0c;找了下资料&#xff0c;资料来自&#xff1a; http://jingyan.baidu.com/article/642c9d34e55bd9644b46f74e.html 我在这里进行转载&#xff1a; Winio驱动在6…

js获取前后几天或者前后几个月的日期

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 &#xff1b; 正文&#xff1a; demo: 1.获取前后几天的日期 // pages/test/test.jsPage({onLoad: function (options) {var day -7;console.log(GetDay(day))}, }) function GetDay(day) {var tim…

nodejs安装、配置及开发工具

学了node一段时间&#xff0c;但是node的安装还是有一点迷糊。今天新换电脑&#xff0c;所以&#xff0c;需要从头开始&#xff0c;发现node的安装还是不顺畅&#xff0c;这篇随笔是之前学的时候写&#xff0c;但是今天再打开看的时候&#xff0c;发现其他好像没有什么内容&…

拨测工具_您可以拨多少钱? 快速简单地介绍有用的工具。

拨测工具by Miguel Bustamante通过Miguel Bustamante 您可以卷曲多少&#xff1f; 快速简单地介绍有用的工具。 (How much can you cURL? A quick and easy intro to a useful tool.) On a good day I can flex a 20 lb weight…twice. Probably. But that’s not the type o…

leetcode第一刷_Recover Binary Search Tree

这是一道好题&#xff0c;思路尽管有&#xff0c;可是提交之后总是有数据过不了&#xff0c;又依照数据改改改。最后代码都没法看了。收到的教训是假设必须为自己的代码加上非常多非常多特殊的限定。来过一些特殊的数据的话。说明代码本身有非常大的漏洞。 这道题&#xff0c;我…

Java中的文件路径

通常情况下&#xff0c;在Java项目中&#xff0c;我们使用的路径都是在拿到类加载路径后&#xff0c;根据相对位置&#xff0c;使用 FilePathTest.class.getResourceAsStream(relativePath)&#xff1b;拿到文件。今天小生不使用classPath&#xff0c;而是直接去使用相对路径来…

js上传文件,上传表单demo 包含后端php

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; <!DOCTYPE html> <html lang"zh"><head><meta charset"UTF-8"><title>Title</title><script src"https://ajax.as…

如何在Tensorflow.js中处理MNIST图像数据

by Kevin Scott凯文斯科特(Kevin Scott) 如何在Tensorflow.js中处理MNIST图像数据 (How to deal with MNIST image data in Tensorflow.js) There’s the joke that 80 percent of data science is cleaning the data and 20 percent is complaining about cleaning the data …

常用图像额文件格式及类型

1、显示一幅二值图像&#xff1a; >> bw zeros(90,90); >> bw(2:2:88,2:2:88) 1; >> imshow(bw); >> 2、利用image函数显示一幅索引图像&#xff1a; >> [X,MAP] imread(E:\STUDY_software\Matlab2016\images\11.jpg); >> image(X); &…

微信小程序实现滑动翻页效果源码附效果图

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 微信小程序实现滑动翻页效果 效果图&#xff1a; 源码&#xff1a; <view class"mainFrame"><swiper class"container" indicator-dots"{{indic…

Ubuntu 系统 文件操作命令

文件和目录的操作 用户主目录下有一个 Desktop (对应,桌面)mkdir dir1 建立一个目录cd 不添加参数,默认回到主目录(用户目录)touch a.txt 建立一个文件mv a.txt Desktop/ 移动到Desktop/中 mkdir dir1cp -r dir1/ dir2 不加-r或者&#xff0d;R的时候&#xff0c;只拷贝文件&am…

firebase 推送_如何使用Firebase向Web应用程序添加推送通知?

firebase 推送by Leonardo Cardoso由莱昂纳多卡多佐(Leonardo Cardoso) 如何使用Firebase向Web应用程序添加推送通知&#xff1f; (How to add push notifications to a web app with Firebase ??) As web applications evolve, it is increasingly common to come across f…

lucene构建同义词分词器

lucene4.0版本号以后 已经用TokenStreamComponents 代替了TokenStream流。里面包含了filter和tokenizer 在较复杂的lucene搜索业务场景下&#xff0c;直接网上下载一个作为项目的分词器&#xff0c;是不够的。那么怎么去评定一个中文分词器的好与差&#xff1a;一般来讲。有两个…

正则匹配出字符串中两串固定字符区间的所有字符

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 效果&#xff1a;匹配两个字符串区间的字符串 代码&#xff1a; var dd[];var str is_img"https://www.baidu.com/"is_img11is_img"https://www.baidu.com/"is…