Unit Testing with NSubstitute
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 Frameworks
- Unit Testing Patterns
- Unit Testing Mocking Libraries
- Why we choose NSubstitute?
- NSubstitute Features & Demos
- References
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
- 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?
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.

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.

Simple Example
Code:


TDD: Test-Driven Development
When to write the tests?
- Write a failing test to prove code or functionality is missing from the end product. (RED)
- Make the test pass by writing production code that meets the expectations of your test. (GREEN)
- Refactor your code. (REFACTOR)
Define TDD Paradigm

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
- Visual Studio Unit Testing Framework
- MSTest
- NUnit
- xUnit.net
- More…
Integrated with Automated Build
- With MSBuild.
- <RunTest>true</RunTest>
- <TestContainer Include="UT*.dll"/>

Unit Testing Patterns
Record – Replay – Verify Model
A model that allows for recording actions on a mock object and then replaying and verifying them.

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:
- Arrange all necessary preconditions and inputs.
- Act on the object or method under test.
- Assert that the expected results have occurred.

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

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

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


Setting a return value

Return for any args

Return from a function

Argument matchers

Replacing return values

Check received calls

Callbacks, When..Do

Throwing exceptions

Raising events

References
- http://xunitpatterns.com/index.html
- http://nsubstitute.github.io/
- http://martinfowler.com/articles/mocksArentStubs.html
- http://www.cnblogs.com/gaochundong/
Unit Testing with NSubstitute的更多相关文章
- [Java Basics3] XML, Unit testing
What's the difference between DOM and SAX? DOM creates tree-like representation of the XML document ...
- Javascript单元测试Unit Testing之QUnit
body{ font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif; } QUnit是一个基于JQuery的单元测试Uni ...
- [Unit Testing] AngularJS Unit Testing - Karma
Install Karam: npm install -g karma npm install -g karma-cli Init Karam: karma init First test: 1. A ...
- C/C++ unit testing tools (39 found)---reference
http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...
- Unit testing Cmockery 简单使用
/********************************************************************** * Unit testing Cmockery 简单使用 ...
- Unit Testing a zend-mvc application
Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in ...
- Unit Testing PowerShell Code with Pester
Summary: Guest blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerS ...
- MVC Unit Testing学习笔记
MVC Unit Testing 参考文档: 1.http://www.asp.net/mvc/overview/testing 2.http://www.asp.net/mvc/tutorials/ ...
- 读书笔记-实用单元测试(英文版) Pragmatic Unit Testing in C# with NUnit
读书笔记-实用单元测试(英文版) Pragmatic Unit Testing in C# with NUnit Author: Andrew Hunt ,David Thomas with Matt ...
随机推荐
- C# 通过反射获取扩展方法
注意,扩展方法本质上是静态方法,所以拿到MethodInfo时,应该这么调用 methodInfo.Invoke(null, new object[]{params}) static IEnumera ...
- [OPENCV] 第一个程序 识别颜色
它可以鉴别出图像中含有给定颜色的所有像素,该算法输入的是图像以及颜色,并返回表示含有指定颜色的像素的二值图像.该算法还需要指定另外一个参数,即对颜色偏差的容忍度. 实现效果 实现后 #include ...
- font-family字体总结
宋体 SimSun黑体 SimHei微软雅黑 Microsoft YaHei微软正黑体 Microsoft JhengHei新宋体 NSimSun新细明体 PMingLiU细明体 MingLiU标楷体 ...
- html学习第三天—— 第13,14章
颜色值缩写 关于颜色的css样式也是可以缩写的,当你设置的颜色是16进制的色彩值时,如果每两位的值相同,可以缩写一半. 例子1: p{color:#000000;} 可以缩写为: p{color: # ...
- angularJS(7)
服务:AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用.AngularJS 内建了30 多个服务. 最常用的服务:$location 服务, $http 服务 ...
- 解决vsftpd的refusing to run with writable root inside chroot错误
参考 http://www.cnblogs.com/CSGrandeur/p/3754126.html 在Ubuntu下用 vsftpd 配置FTP服务器,配置 “ sudo chmod a-w /h ...
- 采用Lambda表达式快速实现实体模型对象转换到DTO
在项目中,采用code first时建立的模型对象不能直接用于数据传输,需要从新根据需求建立Dto对象 为什么需要建立Dto对象呢? DTO即数据传输对象.之前不明白有些框架中为什么要专门定义DTO来 ...
- [译]App Framework 2.1 (2)之 Get Involved
App Framework API 第二篇 原文在此:http://app-framework-software.intel.com/documentation.php#intro/involved ...
- 转行|如何成为企业想要的Android工程师
没经验 一来没钱 二来没时间 三来投简历没人要 四来就算忽悠进去了,也做不了,亚历山大,迟早被踢 1.做好手上的工作 不要裸辞 忌讳心猿意马的心态,当有两个选择的时候,往往 所以要专注于当下手头上唯一 ...
- tungsten抽取和应用mysql binlog
首先举例说明 api的基本使用方式 首先进行配置 , 可以看到源数据库和目的数据库 TungstenProperties tp=new TungstenProperties(); tp.setStri ...