O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

Unit testing basics with NUnit and Visual Studio

913 visualizações

Publicada em

Learn unit testing basic step by step.

Publicada em: Tecnologia, Educação
  • Seja o primeiro a comentar

Unit testing basics with NUnit and Visual Studio

  1. 1. Unit Testing in .net
  2. 2. Technical reasons  Tests encourage better design sooner  Tests are the best documentation  Tests are your safety net  Every day use  Major refactoring freedom
  3. 3. Test Types  Unit Testing  Tests an atomic unit of code, such as a method  Integration Testing  Tests two or more software modules as a group  User Acceptance Testing  Tests performed by end users to validate specific features  TDD Test  Look like a unit test, feels like an user acceptance test
  4. 4. Unit Testing Defined  A unit test is a 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. The Art of Unit Testing by Roy Osherove
  5. 5. Unit vs. Integration Testing  Unit tests exercise and test a single piece of code  Integration tests exercise and test many units of code that work together as a whole
  6. 6. Code to Unit Test  Unit tests should target logical code  Logical code is defined as any piece of code that contains any type of decision making logic such as IF statements, loops, switch statements, calculations etc.
  7. 7. Properties of a Good Unit Test  It is Automated and Repeatable  It is Easy to Implement  It Can Be Run in the Future  It Can Be Run by Anyone  It Can Run at the Push of a Button  It Runs Quickly
  8. 8. Test Project Creation Guidelines  Demo and setup
  9. 9. Test Project Creation Guidelines  Create separate test projects for unit tests and integration tests. This will allow for calling unit tests from the build process in the future  Test project naming convention:  [Project Name].UnitTests  [Project Name].IntegrationTests
  10. 10. Test Class Guidelines  Each class being tested should have its own test class defined (the one-test-class-per-class pattern)  Create utility methods if multiple tests need the same functionality  Test class naming convention:  [Class Name]Tests.cs where Class Name is the name of the class being tested.
  11. 11. Test Method Guidelines  Each public method exposed by the class under test should be tested // Configure/Setup // Action // Assert Note: you can test Internal methods (if required). Use InternalsVisibleTo[<Project>.UnitTests] attribute in AssemblyInfo.  Test method naming convention:  [Method Name]_[Scenario]_[ExpectedBehavior] Examples: ValidateCreditCard_InvalidExpiryDate_ThrowsException() ValidateCreditCard_InvalidAddress_ThrowsException()
  12. 12. NUNIT Test Framework Attributes Define class as a TestClass [TestFixture] public class FileManagerTests { } Define a test method test a single method and expected behavior [Test] public void IsValidFileName_InvalidFilePath_ThrowException(){ } Use setup attribute to call required code before each test in the class. For e.g. InitializeConfiguration()
  13. 13. Test Project Structure  The test project, class, and method guidelines allow us to do the following:  Look at a project and find all related tests  Look at a class and find all related tests  Look at a class method and find all related tests
  14. 14. Unit Testing Techniques  An external dependency is an object in the system under test over which you have no control.  External dependencies need to be “faked”. It is necessary to fake those dependencies to make sure the scope of the code being tested is limited to the system under test.
  15. 15. Unit Testing Techniques  Stub:  A controllable replacement for an existing external dependency in the system.  It allows to test code without dealing with dependencies directly, since those dependencies are effectively simulated.  can never fail a test  Mock:  A fake object in the system that decides whether the unit test passed or failed.  The unit test verifies the state of the mock object to determine success or failure.  may result in failed tests.  State of the object would be checked as asserts gets created against them.
  16. 16. .. And Dependency injection  Decouple the components by injecting them via constructors.  Increase the testability.
  17. 17. Mocks and Stubs – Things to Consider  Writing mocks and stubs takes time, so keep them as simple as possible  Focus on Reusability  Inject stub/mocks to replace the dependency component.  Use available libraries e.g. RhinoMocks
  18. 18. Test Code Coverage  Above 95% code coverage  Do not confuse with covering entire assembly .  Method level would be sufficient  Use tools(Inbuilt or third party).
  19. 19. Hallmarks of Quality Tests  Trustworthiness – Developers will want to run trustworthy tests, which are tests whose results are reliable  Maintainability – Non-maintainable tests are short-lived. The more focused and short the test methods, the more maintainable.  Readability - If the tests are not easily readable, they will most likely be less trustworthy and less maintainable
  20. 20. Signs of Trustworthy Tests  When a test passes, your first reaction is not to say “I’ll step through the debugger just to make sure”  When a test fails, your first reaction is not to say, “Well, that does not mean the code is not working”  When you run the tests, your first reaction is not to say “Yes but, what about this scenario?” due to lack of coverage
  21. 21. Why UnitTests?  Saves your time of debugging via print statements, traces or VS debugger.  Saves other’s time from stepping through your code to ensure it’s working.  Reduce bugs in early stage  Better design
  22. 22. Resources  Nunit  http://www.nunit.org  Code Coverage Overview  http://msdn.microsoft.com/en- us/library/cc667391(v=VS.90).aspx  Rhino Mocks  http://ayende.com/blog/tags/rhino-mocks
  23. 23.  Blog – www.cshandler.com About me Amit Choudhary Microsoft MVP Visual C# Twitter – @vendettamit