Monday, February 28, 2011

Work on Mocketry

Mocketry is a Mocketry is Smalltalk mock object framework.

To load it in Pharo:
Gofer it
  squeaksource: 'MetacelloRepository';
  package: 'ConfigurationOfMocketry';
  load.

(Smalltalk at:#ConfigurationOfMocketry) project latestVersion load.


I've done the first part of the Picasa screencast in a TDD way using Mocketry to prevent external HTTP requests.
Gofer it
 squeaksource: 'LaurentLSandbox';
 package: 'Picasa';
 load.

As the requests are done using HTTPSocket class>>httpGet:, one way is to give a mock to PicasaSearch so we can check (and stub) the HTTP request:
PicasaSearchTwoRoughSeaTest>>setUp
  [:mockHTTPSocketClass|
    [photos := PicasaSearch new
        httpSocketClass: mockHTTPSocketClass;
        addKeyword: 'rough';
        addKeyword: 'sea';  
        maxResult: 2;
        photos.] 
 
     should strictly satisfy: [
        (mockHTTPSocketClass httpGet: 
          'http://picasaweb.google.com/data/feed/api/all?q=rough+sea&max-results=2')
        willReturn: self fixtureXMLResponseForTwoRoughSea] 
  ] runScenario.

#fixtureXMLResponseForTwoRoughSea will return an XML string and test methods will check that it is correctly parsed.

In PicasaSearch:
httpGetDocument 
  |url| 
  url := String streamContents: [:aStream|
  aStream 
    nextPutAll: 'http://picasaweb.google.com/data/feed/api/all?q=';
    nextPutAll: ('+'  join: self keywords);
    nextPutAll: '&max-results=';
    nextPutAll: self maxResult asString.    
  ].  

  ^ (self httpSocketClass httpGet: url).


See that mocketry extends BlockClosure to create mocks:
[:myFirstMock :mySecondMock|
"do stuff with mocks"
] runScenario

and set up expectations:
[:myFirstMock :mySecondMock|
  [ "do stuff with mocks" ] 
  should strictly satisfy: 
  [ "what is expected on mocks" ]  
] runScenario

See HelpSystem book loaded with Mocketry for several examples.

Comments and better code propositions are welcome.

No comments:

Post a Comment