Test Driven Development
hard to test software write test first
manual test
- not repeatable
- not structured
- not standardised reporting
unit testing
- a method/a database query/stored proc/a dynamic web page
- automated,self-validating,consistent/repeatable,independent,readable,fast
AAA Arrange Act Assert : Given When Then
void testConnotOverDraw(){ //Arrange BankAccount ac = new BankAccount(5000); //Act Ac.withdraw(3000); //Assert Assertequals(2000,ac.get_balance()); }
Unit Testing with JUnit
one-off setup/teardown assertThat()
Hamcrest matchers
- more expressive
- clearer
- no need for optional String message
is(),equalTo() not() instanceOf() nullValue(),notNullValue() sameInstance() lessThanOrEqualTo() allOf(),anyOf() endsWith() closeTo() hasItem()
Define a Custom Macher
todO:
grouping tests together
@RunWith(value=Suite.class)
Test with Mock
NumberGenerator mocGenerator = createMock(NumberGenerator.class); for(int i=1;i<7;i++){ expect(mocGenerator.generate(anyInt)).andReturn(i); } replay(mockGenerate); Lottery lotto = new Lottery(mockGenerate); Set<Integer> numbers = lotto.generateRandomSet(); assertThat(lotto.formatNumbers(numbers),is("1-2-3-4-5-6")) verify(mockGenerate);
EasyMock: Introduction
- Create required mock objects,e.g. via createMock()
- Create an instance of the CUT,replacing dependencies on real collaborators with mocks
- set expections on mock(s)
- call replay(),which indicates expectation-setting has finished
- invoke a method on CUT, to verify if the mock get the calls we expected
- Optionally, make assertions(as before)
Note: To use EasyMock, you must ensure easymock.jar is on the classpath, and that you import the org.easymock.EasyMock class. The EasyMock class contains a whole bunch of important static methods, e.g. createMock(), expect(), replay(), and verify()
There are several ways to create a mock object in EasyMock
- createStrickMock(): 1. no unexpected method calls 2. the order of the calls must be as per expectations.
- createMock: 1. no unexpected calls 2.
- createNiceMock:
EasyMock: Setting expections
- for a void method, use expectLastCall()
- if you want to specify the cardinality, use: times(int count)
EasyMock: Replay and verify
- replay(mockRequest,mockResponse ) this indicates you’ve finished setting expections,and are ready to check if the expected method invocations are actually made
- verify: this verifies that the tested object did perform all the method calls that were expected of it.
Variations(变种)
- Classes can be mocked : add cglib-nodep and objenesis jars to the classpath
- make your test class extend EasyMockSupport : replayAll() verifyAll()