Component Testing (Unit Testing)

Slides:



Advertisements
Similar presentations
Unit testing in.Net. Copyright 2007 Tikal Knowledge, Ltd. | 2 | Agenda Introduction Visual Studio built-in support Open source frameworks Working together.
Advertisements

Introduction to Unit Testing Svetlin Nakov Telerik Corporation
Integrated Development Environments, Source Control Repositories, Automated Testing Tools, Bug Tracking, Code Analysis Tools, Build Tools, Project Hosting.
What is Unit Testing? How TDD Works? Tsvyatko Konov Telerik Corporation
TDD Test-Driven Development. JUnit 4.0 To use annotations need to import org.junit.Test To use assertion need to import org.junit.Assert.* No need to.
Unit testing C# classes “If it isn’t tested it doesn’t work” Unit testing C# classes1.
TDD,BDD and Unit Testing in Ruby
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Test Driven Development TDD. Testing ”Testing can never demonstrate the absence of errors in software, only their presence” Edsger W. Dijkstra (but it.
SENG 403, Winter 2012 SENG 403 – Winter  Exploring unit-testing frameworks in.NET  Writing our first test with NUnit  Unit Testing in Visual.
Lecture 6 Software Testing and jUnit CS140 Dick Steflik.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Introduction to Unit Testing Jun-Ru Chang 2012/05/03.
Unit Testing and Mocking
Code Correctness, Readability, Maintainability Telerik Software Academy Telerik School.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Dr. Tom WayCSC Testing and Test-Driven Development CSC 4700 Software Engineering Based on Sommerville slides.
Testing. 2 Overview Testing and debugging are important activities in software development. Techniques and tools are introduced. Material borrowed here.
Unit Testing Building Rock-Solid Software SoftUni Team Technical Trainers Software University
1.  Writing snippets of code that try to use methods (functions) from your program.  Each snippet should test one (and only one) function......by calling.
Testing Chapter 10. Types of Testing Test typeEnsures that Unit testEach independent piece of code works correctly. Integration testAll units work together.
A Practical Guide To Unit Testing John E. Boal TestDrivenDeveloper.com.
Introduction to JUnit 3.8 SEG 3203 Winter ‘07 Prepared By Samia Niamatullah.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
Unit Tests Руслан Трифонов Omegasoft Ltd.. Съдържание 1.Въведение 2.Unit test patterns 2.1. Pass/fail patterns 2.2. Collection management patterns 2.3.
Unit Testing in JavaScript with Mocha, Chai and Karma SoftUni Team Technical Trainers Software University
CPSC 871 John D. McGregor Module 8 Session 1 Testing.
Unit Testing Building Rock-Solid Software Svetlin Nakov Technical Trainer Software University
Unit Testing. F-22 Raptor Fighter Manufactured by Lockheed Martin & Boeing How many parts does the F-22 have?
Well-behaved objects Main concepts to be covered Testing Debugging Test automation Writing for maintainability Objects First with Java - A Practical.
Unit Testing Fundamentals and NUnit Svetlin Nakov National Academy for Software Development academy.devbg.org Veselin Georgiev National Academy for Software.
Northwest Arkansas.Net User Group Jay Smith Tyson Foods, Inc. Unit Testing nUnit, nUnitAsp, nUnitForms.
Unit testing with NUnit Anne Lam & Chris James CMPS 4113 – Software Engineering April 15, 2015.
Software Engineering Lecture 11 Software Testing Presenter: Josef Hallberg 1.
CPSC 372 John D. McGregor Module 8 Session 1 Testing.
SWE 434 SOFTWARE TESTING AND VALIDATION LAB2 – INTRODUCTION TO JUNIT 1 SWE 434 Lab.
Unit Testing.
Building Rock-Solid Software
Unit Testing - solid fundamentals
Test-driven development
Testing Verification and the Joy of Breaking Code
TESTING TEST DRIVEN DEVELOPMENT
Unit Testing with Mocha
John D. McGregor Session 9 Testing Vocabulary
Unit Testing with xUnit.net
Introduction to Unit Testing in JavaScript
Introduction to JUnit CS 4501 / 6501 Software Testing
Development and Testing Ch4.1. Algorithm Analysis
Test Driven Development 1 November Agenda  What is TDD ?  Steps to start  Refactoring  TDD terminology  Benefits  JUnit  Mocktio  Continuous.
Chapter 8 – Software Testing
Testing and Debugging.
John D. McGregor Session 9 Testing Vocabulary
Unit testing C# classes
Unit Testing & Test-Driven Development for Mere Mortals
John D. McGregor Session 9 Testing Vocabulary
Test-first development
History, Characteristics and Frameworks
Design and Programming
Testing and Test-Driven Development CSC 4700 Software Engineering
Introduction to JUnit CS 4501 / 6501 Software Testing
Introduction to JUnit IT323 – Software Engineering II
Unit Testing & Test-Driven Development for Mere Mortals
Testing Acknowledgement: Original slides by Jory Denny.
CS 240 – Advanced Programming Concepts
Tonga Institute of Higher Education IT 141: Information Systems
Unit Testing for the Absolute Beginner
CMSC 202 Exceptions 2nd Lecture.
Tonga Institute of Higher Education IT 141: Information Systems
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Presentation transcript:

Component Testing (Unit Testing) Introduction to Unit Testing Nikolay Kostov Technical Trainer http://www.nikolay.it Telerik QA Academy http://qaacademy.telerik.com

Table of Contents What is Unit Testing? * Table of Contents What is Unit Testing? Code and Test vs. Test Driven Development Unit testing Frameworks Visual Studio Team Test Nunit Gallio Unit Testing Best Practices

What is Unit Testing?

* Unit Test – Definition A unit test is a piece of code written by a developer that exercises a very small, specific area of functionality of the code being tested. “Program testing can be used to show the presence of bugs, but never to show their absence!” Edsger Dijkstra, [1972]

Manual Testing You have already done unit testing Manually, by hand Manual tests are less efficient Not structured Not repeatable Not on all your code Not easy to do as it should be

Unit Test – Example int Sum(int[] array) { sum = 0; for (int i=0; i<array.Length; i++) sum += array[i]; return sum; } void TestSum() if (Sum(new int[]{1,2}) != 3) throw new TestFailedException("1+2 != 3"); if (Sum(new int[]{-2}) != -2) throw new TestFailedException("-2 != -2"); if (Sum(new int[]{}) != 0) throw new TestFailedException("0 != 0");

Unit Testing – Some Facts Tests are specific pieces of code In most cases unit tests are written by developers, not by QA engineers Unit tests are released into the code repository along with the code they test Unit testing framework is needed Visual Studio Team Test (VSTT) NUnit, MbUnit, Gallio, etc.

Unit Testing – More Facts All classes should be tested All methods should be tested Trivial code may be omitted E.g. property getters and setters Ideally all unit tests should pass before check- in into the source control repository

Why Unit Tests? Unit tests dramatically decrease the number of defects in the code Unit tests improve design Unit tests are good documentation Unit tests reduce the cost of change Unit tests allow refactoring Unit tests decrease the defect-injection rate due to refactoring / changes

Code and Test vs. Test Driven Development

Unit Testing Approaches "Code and Test" approach Classical approach "Test First" approach Test-driven development (TDD)

Code and Test Approach Write code Write unit test Run and succeed Time flow

Test Driven Development (TDD) Pick а test Compile and fail Write code to pass test Write enough code to compile Run test and fail Create a test list Time flow Write test Remove duplication

Why Test Driven Development? Helps find design issues early and avoids rework Writing code to satisfy a test is a focused activity – less chance of error Tests will be more comprehensive than when written after code

Unit Testing Frameworks * Unit Testing Frameworks

Unit Testing Frameworks JUnit The first popular unit testing framework Based on Java, written by Kent Beck & Co. Similar frameworks have been developed for a broad range of computer languages NUnit – for C# and all .NET languages cppUnit, jsUnit, PhpUnit, PerlUnit, ... Visual Studio Team Test (VSTT) Developed by Microsoft, integrated in VS

Visual Studio Team Test (VSTT) * Visual Studio Team Test (VSTT)

Visual Studio Team Test – Features Team Test (VSTT) is very well integrated with Visual Studio Create test projects and unit tests Execute unit tests View execution results View code coverage Located in the assembly Microsoft.VisualStudio.QualityTools.Uni tTestFramework.dll

Visual Studio Team Test – Attributes Test code is annotated using custom attributes: [TestClass] – denotes a class holding unit tests [TestMethod] – denotes a unit test method [ExpectedException] – test causes an exception [Timeout] – sets a timeout for test execution [Ignore] – temporary ignored test case [ClassInitialize], [ClassCleanup] – setup / cleanup logic for the testing class [TestInitialize], [TestCleanup] – setup / cleanup logic for each test case

Assertions Predicate is a true / false statement Assertion is a predicate placed in a program code Indicates that the developer thinks that the predicate is always true at that place If an assertion fails, the method call does not return and an error is reported Example: Assert.AreEqual(expectedValue, actualValue, "Error message.");

VSTT – Assertions Assertions check condition and throw exception if condition is not satisfied Comparing values AreEqual(expected value, calculated value [,message]) – compare two values for equality Comparing objects AreSame(expected object, current object [,message]) – compares object references

VSTT – Assertions (2) Checking for null value Conditions IsNull(object [,message]) IsNotNull(object [,message]) Conditions IsTrue(condition) IsFalse(condition) Forced test fail Fail(message)

The 3A Pattern Arrange all necessary preconditions and inputs Act on the object or method under test Assert that the expected results have occurred [TestMethod] public void TestDeposit() { BanckAccount account = new BanckAccount(); account.Deposit(125.0); account.Deposit(25.0); Assert.AreEqual(150.0, account.Balance, "Balance is wrong."); }

Code Coverage Shows what percent of the code we’ve covered We may have pointless unit tests that are calculated in the code coverage 70-80% of coverage is excellent

VSTT – Example public class Account { private decimal balance; public void Deposit(decimal amount) this.balance += amount; } public void Withdraw(decimal amount) this.balance -= amount; public void TransferFunds( Account destination, decimal amount) { … } public decimal Balance

VSTT – Example (2) using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class AccountTest { [TestMethod] public void TransferFunds() Account source = new Account(); source.Deposit(200.00M); Account dest = new Account(); dest.Deposit(150.00M); source.TransferFunds(dest, 100.00M); Assert.AreEqual(250.00M, dest.Balance); Assert.AreEqual(100.00M, source.Balance); }

VSTT – Screenshot

Visual Studio Team Test Live Demo

NUnit http://www.nunit.org/index.php?p=download

NUnit – Features Test code is annotated using custom attributes Test code contains assertions Tests organized as multiple assemblies Two execution interfaces GUI: nunit-gui.exe Console: nunit-console.exe

NUnit – Features (2) NUnit provides: Creating and running tests as NUnit Test Projects Visual Studio support

NUnit – Attributes [TestFixture] – Marks a class that contains tests Should be a public class [Test] – Marks a method as an unit test [TestFixtureSetUp] – Indicate a setup method that will be ran once before all other tests Called before the tests are started

NUnit – Attributes (2) [TestFixtureTearDown] – Indicate a tear down method that will be ran once after all other tests have run Called after all the tests have finished [SetUp] – indicates a setup method that should be ran before each of the tests [TearDown] – used to indicate a tear down that method should be ran after each of the tests

NUnit – Attributes (3) [ExpectedException(typeof(Exception))] When you expect an exception to be thrown Will only pass if exception type was thrown [Ignore("Not ready for primetime")] Indicates test that is not ready, or should not be run

NUnit – Assertions Using NUnit.Framework.Assert class Assertions check condition and throw exception if condition is not satisfied Comparing values AreEqual(expected value, calculated value [, message]) - compare values

NUnit – Assertions (2) Comparing objects Conditions IsNull(object [, message]) IsNotNull(object [, message]) AreSame(expected object, current object [,message]) – compare object references Conditions IsTrue(condition) IsFalse(condition)

NUnit – Assertions (3) Forced test fail Explicit tests (ignored unless run explicitly) [TestFixture, Explicit] [Test, Explicit] Categories [TestFixture, Category("LongRunning")] [Test, Category("Long")]

NUnit – Example: Class public class Account { private float balance; public void Deposit(float amount) balance+=amount; } public void Withdraw(float amount) balance-=amount; public void TransferFunds( Account destination, float amount) { … } public float Balance { get { return balance; } }

NUnit – Example: Test using NUnit.Framework; [TestFixture] public class AccountTest { [Test] public void TransferFunds() Account source = new Account(); source.Deposit(200.00F); Account dest = new Account(); dest.Deposit(150.00F); source.TransferFunds(dest, 100.00F); Assert.AreEqual(250.00F, dest.Balance); Assert.AreEqual(100.00F, source.Balance); }

SetUp & TearDown Timeline Begin Tests Call TestFixtureSetUp Call SetUp Call ExampleTestOne Call TearDown Call ExampleTestTwo Call TestFixtureTearDown End Tests

NUnit – Screen Shots

NUnit – Screen Shots (2)

NUnit – Screen Shots (3)

NUnit – Screen Shots (4)

Gallio

The Gallio Automation Platform An open, extensible, and neutral system for .NET using many test frameworks Gallio can run tests from MbUnit, MSTest, NUnit, xUnit.Net, csUnit, and RSpec Provides a common object model, runtime services and tools (such as test runners) May be leveraged by any number of test frameworks www.gallio.org

Interfaces Gallio includes its own interfaces: Echo Icarus Command-line runner Icarus Windows GUI

Gallio – Screen Shots

Gallio – Screen Shots (2)

Gallio – Screen Shots (3)

Gallio – Screen Shots (4)

Gallio – Screen Shots (5)

Unit Testing Best Practices * Unit Testing Best Practices

Naming Standards for Unit Tests The test name should express a specific requirement that is tested Usually prefixed with [Test] E.g. TestAccountDepositNegativeSum() The test name should include Expected input or state Expected result output or state Name of the tested method or class

Naming Standards for Unit Tests – Example Given the method: with requirement to ignore numbers greater than 100 in the summing process The test name should be: TestSum_NumberIgnoredIfGreaterThan100 public int Sum(params int[] values)

When Should a Test be Changed or Removed? Generally, a passing test should never be removed These tests make sure that code changes don’t break working code A passing test should only be changed to make it more readable When failing tests don’t pass, it usually means there are conflicting requirements

When Should a Test be Changed or Removed? (2) Example: New features allows negative numbers [ExpectedException(typeof(Exception), "Negatives not allowed")] void TestSum_FirstNegativeNumberThrowsException() { Sum (-1,1,2); }

When Should a Test be Changed or Removed? (3) New developer writes the following test: Earlier test fails due to a requirement change void TestSum_FirstNegativeNumberCalculatesCorrectly() { int sumResult = sum(-1, 1, 2); Assert.AreEqual(2, sumResult); }

When Should a Test be Changed or Removed? (4) Two course of actions: Delete the failing test after verifying if it’s valid Change the old test: Either testing the new requirement Or test the older requirement under new settings

Tests Should Reflect Required Reality What’s wrong with the following test? A failing test should prove that there is something wrong with the production code Not with the unit test code int Sum(int a, int b) –> returns sum of a and b public void Sum_AddsOneAndTwo() { int result = Sum(1,2); Assert.AreEqual(4, result, "Bad sum"); }

What Should Assert Messages Say? Assert message in a test is one of the most important things Tells us what we expected to happen but didn’t, and what happened instead Good assert message helps us track bugs and understand unit tests more easily Example: "Withdrawal failed: accounts are not supposed to have negative balance."

What Should Assert Messages Say? (2) Express what should have happened and what did not happen “Verify() did not throw any exception” “Connect() did not open the connection before returning it” Do not: Provide empty or meaningless messages Provide messages that repeat the name of the test case

Avoid Multiple Asserts in a Single Unit Test void TestSum_AnyParamBiggerThan1000IsNotSummed() { Assert.AreEqual(3, Sum(1001, 1, 2); Assert.AreEqual(3, Sum(1, 1001, 2); Assert.AreEqual(3, Sum(1, 2, 1001); } Avoid multiple asserts in a single test case If the first assert fails, the test execution stops for this test case Affect future coders to add assertions to test rather than introducing a new one

Unit Testing – The Challenge The concept of Unit Testing has been around for many years New methodologies in particular XP, have turned unit testing into a cardinal foundation of software development Writing good & effective Unit Tests is hard! This is where supporting integrated tools and suggested guidelines enter the picture The ultimate goal is tools that generate unit tests automatically

Mock Objects Usage Q: When should mock objects be used? A: Mock objects are used when one needs to replace or remove dependencies from code under test Example: Class LoginManager manages user logins with the following responsibility: When login fails, class reports to a logger class

Mock Objects Usage (2) The unit test should test the class logic Without having to configure or rely on the availability of the logger So we replace the logger class with a "fake" one, a mocking object

Component Testing (Unit Testing) ? ? ? ? ? Questions? ? ? ? ? ? http://academy.telerik.com

Exercises Write three classes: Student, Course and School. Students should have name and unique number (inside the entire School). Name can not be empty and the unique number is between 10000 and 99999. Each course contains a set of students. Students in a course should be less than 30 and can join and leave courses. Write VSTT tests for these two classes Use 2 class library projects in Visual Studio: School.csproj and TestSchool.csproj Execute the tests using Visual Studio and check the code coverage. Ensure it is at least 90%.

* Useful Links A Unit Testing Walkthrough with Visual Studio Team Test – http://msdn.microsoft.com/en- us/library/ms379625(VS.80).aspx NUnit – www.nunit.org Extreme Programming – www.extremeprogramming.org XP Programming – www.xprogramming.com Advanced Unit Testing – www.codeproject.com/csharp/autp1.asp