Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Unit Testing

Deep Focus
August 06, 2014

Unit Testing

Deep Focus

August 06, 2014
Tweet

More Decks by Deep Focus

Other Decks in Technology

Transcript

  1. Real World (but simple) example task: We’ll use Asp.Net to

    make it more real. StructureMap for IoC/DI. NSubstitute for faking dependencies. NLog as a 3rd party dependency example. Render a page / partial / widget: • Downloads latest currency rate from web service. • Serves a cached data before it expires. • If a web service call fails, log an error (possibly by email) • Should return null model if unable to get result. (view will render N/A state let's see some code...
  2. What do we need to test? • We only test

    our own control flow code: (code that has some kind of logic. Ex. if or switch statements, loop. • In Asp.Net MVC, what do we test? ◦ controllers ◦ services ◦ don’t test framework functionality
  3. Difference between Stubs and Mocks: Stub fakes return value. Mock

    keeps track of interactions. Code Under Test Code Under Test Stub object Mock object Assert Assert Test Test Communication Communication Stub can’t fail the test. The asserts are always against the code under test. The test uses the mock object to verify that the test passes.
  4. Isolation Frameworks Constrained • Rhino Mocks, Moq, NMock, EasyMock, •

    NSubstitute, and FakeItEasy. • limited to the same compiler rules as regular code. • Unable to fake static methods, nonvirtual methods, nonpublic methods, private methods, sealed classes, classes with private constructors. Unconstrained • Typemock Isolator, JustMock and MS Fakes. • Based around profiling API in .NET • Can fake third-party systems you can’t control and that are potentially very hard to test, such as if your objects have to inherit from the base class of a third-party product. • easy to fake things that aren’t needed, instead of looking at the unit of work at a higher level • Test can become unmaintainable because you’re faking APIs that you don’t own.
  5. What make a good unit test • Trustworthiness ◦ Avoid

    test logic ◦ Test only one concern • Maintainability ◦ Testing private method ◦ Duplication ◦ Test isolation ◦ Avoid overspecification • Readability ◦ Naming tests and variables MethodUnderTest_Scenario_Behavior() ◦ Separating asserts from actions (do assert on separate line) ◦ Don’t abuse setting up and tearing down methods