Using Xcode snippets is a great way to simplify creating unit tests.
With the exception of the first snippet, these assume that the unit test case file has already been created as described on the templates page, meaning that the object under test has been instantiated in setUp, etc.
Unit Test Setup/Teardown
This snippet can be used to add the setUp and tearDown methods to a Unit Test case file.
Note that the custom template creates these already, so these are only needed if the file was previously created without using the custom template.
// Insert at top of Unit Test Case file - (void)setUp { self.<#yourObject#> = [[<#YourObjectClass#> alloc]init]; } - (void)tearDown { self.<#yourObject#> = nil; }
Basic Unit Test
This is the most basic sort of test. The code being tested is called, then a result or side effect is asserted. Often the method under test returns a value that can be directly tested in the assertion.
- (void)test<#SomethingOrOther#> { [self.<#yourObject#> <#methodUnderTest#>]; STAssertTrue( <#testForSuccess#>, @"<#Explanation of error#>"); }
Unit Test With Mock Expect
This test creates a mock object and assigns it to a property on the object under test.
The assumption is that the method to be tested depends on the object assigned to that property to return a particular value.
- (void)test<#MethodUsingMockExpects#> { id mock = [OCMockObject mockForClass:[<#mockedClass#> class]]; [[[mock expect]andReturnValue:OCMOCK_VALUE((<#type#>){<#value#>})]<#method#>]; [self.<#yourObject#> set<#Property#>:mock]; <#type#> expectedValue = <#expected value#>; <#type#> retVal = [self.<#yourObject#> <#testMethod#>]; [[mock verify]; STAssertTrue(retVal == expectedValue,@"Returned value %d was expected to be %d",retVal,expectedValue) }
Unit Test Using a Partial Mock
This test will create a partial mock of the object under test. This allows calling a method that in turn calls a second method on the same object. The partial mock allows mocking the second method call.
- (void)test<#MethodBeingTested#> { id mock = [OCMockObject partialMockForObject:self.<#yourObject#>]; [[mock expect]<#expectedMethodOnYourObject#>]; [mock <#methodUnderTest#>]; [mock verify]; }