<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7502287165501666317</id><updated>2011-11-27T16:05:53.559-08:00</updated><category term='Mocks Mockito'/><category term='unit testing conventions naming variables'/><category term='mockito mocks junit answer'/><title type='text'>Unit Testing Guide</title><subtitle type='html'>A Unit Testing Guide. Learn about mock objects, TDD, and general Unit Testing. Overall this is a information for Standards and Guidelines that may make Unit Testing easier.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://unittestingguide.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7502287165501666317/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://unittestingguide.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>J Bruckal</name><uri>http://www.blogger.com/profile/15402821288898175472</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>3</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7502287165501666317.post-5389592382630185445</id><published>2010-03-03T23:14:00.000-08:00</published><updated>2010-03-03T23:19:03.922-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='mockito mocks junit answer'/><title type='text'>Using Mockito to Unit Test real objects with 'Answer'</title><content type='html'>As a follow up to my previous post, this is how to Unit Test with &lt;a href="http://www.junit.org/"&gt;JUnit&lt;/a&gt; and &lt;a href="http://mockito.googlecode.com/svn/branches/1.8.0/javadoc/org/mockito/Mockito.html"&gt;Mockito&lt;/a&gt; if a void method was called instead to move the User.&lt;br /&gt;&lt;br /&gt;Take this code as an example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public void handleMoveForwardRequest(String[] command)&lt;br /&gt;{&lt;br /&gt;        // userId should be the first element&lt;br /&gt;        User user = getUser(command[0]);&lt;br /&gt;        movement.moveUserForward(user);&lt;br /&gt;        // this depends on the socket server API for the exact call&lt;br /&gt;        extension.sendTheResponse(command, user, user.getCurrentLocation());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This code is a little unrealistic, but humour me for this example. Assume that we can pass in a mocked Movement with a setter. We are going to use Mockito's 'answer' call to update the location for the User (which cannot be mocked). They suggest not to use it, but we aren't testing the Movement class.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;//Assume that the mock objects were previously instantiated&lt;br /&gt;@Test&lt;br /&gt;public void canMoveForward()&lt;br /&gt;{&lt;br /&gt;    String[] command = new String[] {"123", "Forward"};&lt;br /&gt;    handler.setMovement(mockMovement);&lt;br /&gt;&lt;br /&gt;    // use hamcrest matchers for the object we're expecting&lt;br /&gt;    when(mockMovement.moveUserForward((User) anyObject()))&lt;br /&gt;.thenAnswer(new Answer() { Object  answer(InvocationOnMock invocation) &lt;br /&gt;{&lt;br /&gt; Object[] args = invocation.getArguments();&lt;br /&gt; User user = (User) args[0];&lt;br /&gt; user.setLocation(user.getCurrentLocationX() + 1, user.getCurrentLocationY());&lt;br /&gt; return "called with arguments: " + args; &lt;br /&gt;} &lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;    User user = getUser(command[0]);&lt;br /&gt;    handler.handleMoveRequest(command);&lt;br /&gt;    verify(mockExtension).sendTheResponse(command, mockUser, user.getCurrentLocation());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;When 'moveUserForward' is called a new 'Answer' is created. It updates the location of the user to some arbitrary value. In this case we added 1 unit to the X location. Our test will pass because the User is a static reference to that object. The location actually is updated for the object that the SUT gets, and the object our test checks for.&lt;br /&gt;&lt;br /&gt;This can seem complicated at first, and it probably isn't necessary because most TDD code is cleaner than this. However, in complicated systems with legacy code you may stumble across a similar situation.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7502287165501666317-5389592382630185445?l=unittestingguide.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://unittestingguide.blogspot.com/feeds/5389592382630185445/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://unittestingguide.blogspot.com/2010/03/using-mockito-to-unit-test-real-objects.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7502287165501666317/posts/default/5389592382630185445'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7502287165501666317/posts/default/5389592382630185445'/><link rel='alternate' type='text/html' href='http://unittestingguide.blogspot.com/2010/03/using-mockito-to-unit-test-real-objects.html' title='Using Mockito to Unit Test real objects with &apos;Answer&apos;'/><author><name>J Bruckal</name><uri>http://www.blogger.com/profile/15402821288898175472</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7502287165501666317.post-2352652147600712166</id><published>2010-02-25T19:43:00.000-08:00</published><updated>2010-03-03T22:52:15.234-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Mocks Mockito'/><title type='text'>Mockito Mocks Rock For Service Requests and Responses</title><content type='html'>My mocking framework of choice when Unit Testing with JUnit is &lt;a href="http://mockito.googlecode.com/svn/branches/1.8.0/javadoc/org/mockito/Mockito.html"&gt;Mockito&lt;/a&gt;. You will hear me preach about readability and, used in conjunction with &lt;a href="http://code.google.com/p/hamcrest/"&gt;hamcrest&lt;/a&gt; matchers, Mockito achieves that.&lt;br /&gt;&lt;br /&gt;Recently I was tasked with testing server side code that could handle requests and sent responses to a socket server. This is not an easy job as most socket servers have their own API which is untouchable. One option is to create an accessor class for the class you are testing and overwriting the method calls. Really not that friendly, but I will post about that option in the future. The second option is using Mockito and developing code that allows Dependency Injection on the socket servers main extension class. If someone requires more details on how to do that, please ask and I will post on that.&lt;br /&gt;&lt;br /&gt;Using Mockito you can verify a response was sent when a request was handled by the class with specific parameters. Take this code as an example (obviously I left this as ambigous as possible and the code is unrealistic):&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public void handleMoveRequest(String[] command, User user)&lt;br /&gt;{&lt;br /&gt;    if (command[0] == "Forward")&lt;br /&gt;    {&lt;br /&gt;        user.moveForward();&lt;br /&gt;        // this depends on the socket server API for the exact call&lt;br /&gt;        extension.sendTheResponse(command, user, user.getCurrentLocation());&lt;br /&gt;    }&lt;br /&gt;    else&lt;br /&gt;    {&lt;br /&gt;        user.moveBackwards();&lt;br /&gt;        extension.sendTheResponse(command, user, user.getCurrentLocation());&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The only way to test the result of the communication with the socket server (from a Unit Testing standpoint) is to Mock the socket server's extension and verify the parameters in the response. Here is how Mockito allows us to do that: &lt;p&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;// Assume that the mock objects were previously instantiated&lt;br /&gt;@Test&lt;br /&gt;public void canMoveForward()&lt;br /&gt;{&lt;br /&gt;    String[] command = new String[] {"Forward"};&lt;br /&gt;    when(mockUser.getCurrentLocation()).thenReturn("1, 1");&lt;br /&gt;    handler.handleMoveRequest(command, mockUser);&lt;br /&gt;    verify(mockUser).moveForward();&lt;br /&gt;    verify(mockExtension).sendTheResponse(command, mockUser, mockUser.getCurrentLocation());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There are many who say there should be one test (assertion) to each test case. Really this is one behaviour that requires 2 checks. If we made separate tests, we would really be duplicating code.&lt;br /&gt;&lt;br /&gt;I leave you with this... what if we wanted to test with a real user? The method 'getCurrentLocation' would probably return a different result after 'moveForward' was called. We can also use Mockito to help with that. I will show how in the next post.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7502287165501666317-2352652147600712166?l=unittestingguide.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://unittestingguide.blogspot.com/feeds/2352652147600712166/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://unittestingguide.blogspot.com/2010/02/mockito-mocks-rocks-for-service.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7502287165501666317/posts/default/2352652147600712166'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7502287165501666317/posts/default/2352652147600712166'/><link rel='alternate' type='text/html' href='http://unittestingguide.blogspot.com/2010/02/mockito-mocks-rocks-for-service.html' title='Mockito Mocks Rock For Service Requests and Responses'/><author><name>J Bruckal</name><uri>http://www.blogger.com/profile/15402821288898175472</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7502287165501666317.post-3554030343846786715</id><published>2010-02-23T20:36:00.000-08:00</published><updated>2010-02-25T20:33:52.760-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='unit testing conventions naming variables'/><title type='text'>Unit Testing: Naming Conventions</title><content type='html'>One of the most important aspects of Unit Testing is readability. If your tests are properly named, as well as your variables, it leads to self-documenting code that is easy to follow. It is common practice in TDD for the progammer to write their own tests. In the companies that I have worked for, it is common for many developers to work on the same code base. If there is no standard or guideline for naming conventions, trying to decipher the code can be a headache.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Naming Conventions&lt;/strong&gt;&lt;br /&gt;I will always stress the importance of testing the behaviour of the code rather than the implementation. This starts with naming your test cases appropriately. Take the following code as an example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;public Connection getConnection(String connectionName)()&lt;br /&gt;{&lt;br /&gt;    Connection connection;&lt;br /&gt;&lt;br /&gt;    switch(connectionName)&lt;br /&gt;    {&lt;br /&gt;        case "PrimaryDb":&lt;br /&gt;            connection = ConnectionType.ONE;&lt;br /&gt;        case "SecondaryDb":&lt;br /&gt;            connection = ConnectionType.TWO;&lt;br /&gt;        default:&lt;br /&gt;            connection = null;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return connection;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now let's analyse the following test case names:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;getConnection_Can_Get_A_Database_Connection&lt;/li&gt;&lt;li&gt;getConnection_canGetTheConnectionForDatabase1&lt;/li&gt;&lt;li&gt;canGetTheConnectionForThePrimaryDatabase&lt;/li&gt;&lt;/ul&gt;From my perspective, the last option is the best one. The first option says nothing about the database we are trying to get a connection for. I also prefer not to over use underscores when separating words. Names become too lengthy. The second option reads nicer than option 1, but the method being tested is indicated. For maintaining code, this can be overkill. If you're writing your tests while you're coding you know how often refactoring occurs. It is a pain to have to manually change the name of each of your tests when changing the name of a method. Most IDE's have a refactoring option which automatically rename all references. The third option specifies the behaviour we are testing and uses camel case so that it is easy to read without being too lengthy. You may need to start each test case with "test" depending on the framework you're using. Most xUnit frameworks allow an "@Test" annotation.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Naming Variables&lt;/strong&gt;&lt;br /&gt;Current IDE's will most likely be equipped with auto-complete features. They can save a huge amount of keystrokes and if you are writing in a losely typed language like PHP, can help ensure you are not accidentally creating new variables. As I mentioned previously, self documenting code is an extremely important aspect of Unit Testing and variable names are part of that. Take the following example of a test case:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: java"&gt;&lt;br /&gt;@Test&lt;br /&gt;public void canReduceTheAmountOfFundsInASavingsAccount()&lt;br /&gt;{&lt;br /&gt;    account = new Account(AccountType.SAVINGS);&lt;br /&gt;    account.setFunds(50);&lt;br /&gt;    account.subtractFunds(35);&lt;br /&gt;    assertEquals(15, account.getFunds());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The test is very easy to follow because the tester used descriptive variables and an Enum to specify the type of account. I have seen people take shortcuts and may name their variables "a" or "act". That may save a couple keystrokes, but it is much harder to follow when revisiting failed test cases.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7502287165501666317-3554030343846786715?l=unittestingguide.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://unittestingguide.blogspot.com/feeds/3554030343846786715/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://unittestingguide.blogspot.com/2010/02/unit-testing-good-looking-vs-bad.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7502287165501666317/posts/default/3554030343846786715'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7502287165501666317/posts/default/3554030343846786715'/><link rel='alternate' type='text/html' href='http://unittestingguide.blogspot.com/2010/02/unit-testing-good-looking-vs-bad.html' title='Unit Testing: Naming Conventions'/><author><name>J Bruckal</name><uri>http://www.blogger.com/profile/15402821288898175472</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
