Unit Testing with NSubstitute

时间:2022-09-24 07:37:47

These are the contents of my training session about unit testing, and also have some introductions about how could we write better unit tests with NSubstitute framework.

The related sessions:

Agenda

Unit Testing Introduction

Unit Testing Classic Definition

A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions afterward. If the assumptions turn out to be wrong, the unit test has failed. A “unit” is a method or function. In OOP, a “unit” is often an entire interface, such as class, but could be an individual method.
  -- from Wikipedia
Kent Beck introduced the concept of unit testing in Smalltalk.

Why Unit Testing?

  • Find Problems Early
    • Find problems in development cycle.
  • Facilitate Changes
    • Allow programmer to refactor code at a later date.
  • Simplify Integration
    • Reduce uncertainty, reduce efforts from integration test.
  • Documentation
    • Sort of living documentation of system.
  • Design by Test Driven
    • Support TDD approach.

Properties of a good unit test

A unit test should have the following properties:
  • It should be automated and repeatable.
  • It should be easy to implement.
  • Once it’s written, it should remain for future use.
  • Anyone should be able to run it.
  • It should run at the push of a button.
  • It should run quickly.

Unit Testing Good Definition

A unit test is an automated piece of code that invokes the method or class being tested and then checks some assumptions about the logical behavior of that method or class. A unit test is almost always written using a unit-testing framework. It can be written easily and runs quickly. It’s fully automated, trustworthy, readable, and maintainable.

What's Logical Behavior?

Logical code is any piece of code that has some sort of logic in it, small as it may be. It’s logical code if it has one or more of the following: an IF statement, a loop, switch or case statements, calculations, or any other type of decision-making code.

Verification Patterns -- State

  • State Verification, also known as State-based Testing.
    • We inspect the state of the system under test (SUT) after it has been exercised and compare it to the expected state.
Unit Testing with NSubstitute
 

Verification Patterns -- Behavior

  • Behavior Verification, also known as Interaction Testing.
    • We capture the indirect outputs of the SUT as they occur and compare them to the expected behavior.
Unit Testing with NSubstitute
 

Simple Example

Code:

Unit Testing with NSubstitute
 
Test:
 
Unit Testing with NSubstitute
 

TDD: Test-Driven Development

When to write the tests?

  1. Write a failing test to prove code or functionality is missing from the end product. (RED)
  2. Make the test pass by writing production code that meets the expectations of your test. (GREEN)
  3. Refactor your code. (REFACTOR)

Define TDD Paradigm

Unit Testing with NSubstitute

TAD: Test After Development

  • Are we TDD-style?
    • No, we are TAD now.
  • Must we do TDD-style coding?
    • No, TDD is a style choice. You can make your own choice.

Unit Testing Frameworks

Framework for Unit Testing

Unit testing frameworks are code libraries and modules that help developers unit-test their code. And also help running the tests as part of an automated build.

What Unit Testing Framework Offer

  • Write tests easily and in a structured manner.
    • Base classes or interfaces to inherit.
    • Attributes to place in code to note the tests to run.
    • Assert classes.
  • Execute one or all of the unit tests.
    • Identify tests in your code.
    • Run tests automatically.
    • Indicate status while running.
  • Review the result of the test runs.
    • Red/Green

xUnit architecture

  • Test Fixtures
  • Test Cases
  • Test Suites
  • Test Execution
  • Assertions

List of Unit Testing Frameworks

Integrated with Automated Build

  • With MSBuild.
    • <RunTest>true</RunTest>
    • <TestContainer Include="UT*.dll"/>

Unit Testing with NSubstitute

Unit Testing Patterns

Record – Replay – Verify Model

A model that allows for recording actions on a mock object and then replaying and verifying them.

Unit Testing with NSubstitute

Arrange – Act – Assert Pattern

  • "Arrange-Act-Assert" is a pattern for arranging and formatting code in UnitTest methods.
    • Each method should group these functional sections, separated by blank lines:
      1. Arrange all necessary preconditions and inputs.
      2. Act on the object or method under test.
      3. Assert that the expected results have occurred.

Unit Testing with NSubstitute

Unit Testing Mocking Libraries

Mocking Library

A mocking library is a set of programmable APIs that make creating mock and stub objects much easier. Mocking libraries save the developer from the need to write repetitive code to test or simulate object interactions.

Other names:

  • Mocking framework
  • Isolation framework

Unit Testing with NSubstitute

Most Features of Mocking Library

  • No Record/Replay idioms to learn.
  • Very low learning curve. Don't even need to read the documentation.
  • No need to learn what's the theoretical difference between a mock, a stub, a fake, a dynamic mock, etc.
  • Strong-typed, no object-typed return values or constraints.
  • Mock both interfaces and classes.
  • Override expectations as needed on tests.
  • Pass constructor arguments for mocked classes.
  • Intercept and raise events on mocks.
  • Intuitive support for out/ref arguments.

Famous Mocking Libraries

  • NSubstitute
  • Moq
  • Rhino Mocks
  • Microsoft Fakes
  • NMock
  • EasyMock.NET
  • TypeMock Isolator
  • JustMock
  • FakeItEasy

The Values of a Good Mocking Library

  • Simple to use. For example, a single point of entry in the API, easy to remember API, or Intelligence guidance.
  • Test Robustness. Making sure the test can live as long as possible while the system changes, and it only breaks when something important to it changes. Things like recursive fakes help a lot there. So does being non strict by default.
  • Helpful. If something is wrong, the user should not feel stupid. Helpful error messages go a long way. Being specific and not surprising the user as much as possible.

Mocking Libraries Comparison

Unit Testing with NSubstitute
-- Roy Osherove, the author of “The Art of Unit Testing”

Why we choose NSubstitute?

Why We Choose NSubstitute?

  • Simple, succinct, pleasant to use.
  • Helpful exceptions.
  • Don't sweat the small stuff.
    • Mock, stub, fake, spy, test double? Nah, just substitute for the type you need!

NSubstitute Features & Demos

Creating a substitute

Unit Testing with NSubstitute

Unit Testing with NSubstitute

Setting a return value

Unit Testing with NSubstitute

Return for any args

Unit Testing with NSubstitute

Return from a function

Unit Testing with NSubstitute

Argument matchers

Unit Testing with NSubstitute

Replacing return values

Unit Testing with NSubstitute

Check received calls

Unit Testing with NSubstitute

Callbacks, When..Do

Unit Testing with NSubstitute

Throwing exceptions

Unit Testing with NSubstitute

Raising events

Unit Testing with NSubstitute

References

Unit Testing with NSubstitute的更多相关文章

  1. &lbrack;Java Basics3&rsqb; XML&comma; Unit testing

    What's the difference between DOM and SAX? DOM creates tree-like representation of the XML document ...

  2. Javascript单元测试Unit Testing之QUnit

    body{ font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif; }           QUnit是一个基于JQuery的单元测试Uni ...

  3. &lbrack;Unit Testing&rsqb; AngularJS Unit Testing - Karma

    Install Karam: npm install -g karma npm install -g karma-cli Init Karam: karma init First test: 1. A ...

  4. C&sol;C&plus;&plus; unit testing tools &lpar;39 found&rpar;---reference

    http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...

  5. Unit testing Cmockery 简单使用

    /********************************************************************** * Unit testing Cmockery 简单使用 ...

  6. Unit Testing a zend-mvc application

    Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in ...

  7. Unit Testing PowerShell Code with Pester

    Summary: Guest blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerS ...

  8. MVC Unit Testing学习笔记

    MVC Unit Testing 参考文档: 1.http://www.asp.net/mvc/overview/testing 2.http://www.asp.net/mvc/tutorials/ ...

  9. 读书笔记-实用单元测试&lpar;英文版&rpar; Pragmatic Unit Testing in C&num; with NUnit

    读书笔记-实用单元测试(英文版) Pragmatic Unit Testing in C# with NUnit Author: Andrew Hunt ,David Thomas with Matt ...

随机推荐

  1. JokeClient-Swift 仿写学习

    required init?(coder aDecoder: NSCoder) 可失败构造器 在init关键字后面添加问号(init?). 可失败构造器会创建一个类型为自身类型的可选类型的对象.你通过 ...

  2. js事件浅析

    js中关于DOM的操作很多,因此js事件机制也就尤为重要. 事件绑定形式: 一. 内联形式 耦合度高,不利于维护 <button onclick="alert('你点击了这个按钮'); ...

  3. SQL Server自动化运维系列——关于数据收集(多服务器数据收集和性能监控)

    需求描述 在生产环境中,很多情况下需要采集数据,用以定位问题或者形成基线. 关于SQL Server中的数据采集有着很多种的解决思路,可以采用Trace.Profile.SQLdiag.扩展事件等诸多 ...

  4. LightOJ1036 A Refining Company(DP)

    题目大概说有一个n*m的格子地图,每个格子有铀或者镭矿.地图最北面的镭矿加工厂,最西面有铀矿加工厂,而要通过在格子里铺设由南向北(镭)或由东向西(铀)的轨道来送矿物到加工厂.一个格子只能铺设一种轨道, ...

  5. 浅谈RAID写惩罚(Write Penalty)与IOPS计算

    介绍 通常在讨论不同RAID保护类型的性能的时候,结论都会是RAID-1提供比较好的读写性能,RAID-5读性能不错,但是写入性能就不如RAID-1,RAID-6保护级别更高,但写性能相对更加差,RA ...

  6. HTML&colon; 字體設置

    針對 font-family 屬性進行詳細設置, 首先我們要瞭解,字體分類: ①無襯線字體: san-serif,一般用於文章標題 ②有襯線字體: serif,一般用在段落處或者非標題部分 當我們設置 ...

  7. Git总结笔记3-把本地仓库推送到github

    说明:此笔记在centos 7 上完成 1.配置公钥 [root@kangvcar ~]# ssh-keygen -t rsa -C "kangvcar@126.com" [roo ...

  8. Good Bye 2018 B&period; New Year and the Treasure Geolocation

    传送门 https://www.cnblogs.com/violet-acmer/p/10201535.html 题意: 在二维空间中有 n 个 obelisk 点,n 个 p 点: 存在坐标T(x, ...

  9. 洛谷P1850 换教室

    令人印象深刻的状态转移方程... f[i][j][0/1]表示前i个换j次,第i次是否申请时的期望. 注意可能有重边,自环. 转移要分类讨论,距离是上/这次成功/失败的概率乘相应的路程. 从上次的0/ ...

  10. 初学Struts2

    1.新建工程,引用Struts2 项目结构如下: 2.Web配置,web.xml: <?xml version="1.0" encoding="UTF-8&quot ...