-
Strict Mork vs Non-strict mork
A strict Mock Object will only allow calling methods on it that were explicitly set via Expectations. Any call that is made which either differs by the parameter values defined, or by the method name, will usually be handled by throwing an exception while the method is being called. That means the test fails on the first unexpected method call to a strict mock object.
-
An Example of Mock
[Test] Public void Analyze_TooShortFileName_ErrorLoggedToService() { MockRepository mocks = new MockRepository(); IWebService simulatedService = mocks.CreateMock(); //pre-arrange setting using(mocks.Record()) { simulatedService.LogError("file name was too short "); } //play LogAnalyzer log = new LogAnalyzer(simulatedService); string tooShortFileName="abc.ext"; log.Analyze(tooShortFileName); -
The difference between mocks and stubs
Stubs can’t fail tests. Mocks can do (or they’d be called Stubs). Stubs simply replace an object so that we can test the object under test without problems. The easiest way to tell we are dealing with a Stub is to notice that the Stub can never ever fail the test. The asserts the test uses are always against the class under test. When using Mocks, on the other hand, The test will use the Mock object to verify if the test failed or not. Again, when using a Mock, the Mock object is the object that we use to see if the test failed or not.
-
Unit Test Best practices
-
Arrange test in your solution
It is common pratice to have a test class per tested class, a test rpoject per tested project and at lest one test method per tested method.
- Naming tests: [MethodUnderTest]_[Scenario]_[ExpectedBehavior]
- Use [Setup] and [TearDown] attributes to reuse code in your tests such as creating and initializing common objects all your tests use.
- Don’t use [Setup] and [TearDown] to initialize or destroy objects which are not shared throughout the test class in all the tests, as it makes the tests less understandable (the reader won’t know which tests use the setup method and which don’t).
-
Arrange test in your solution
-
Value object and Persistance
It is confusing to mixed value object with its persistence. We know value has has no identity. How about primary key in database. Every table in database has an primary key. Isn't that key the identity of value object if we want to persist the value object to database? Here we mix the domain model with the persistence.