Wednesday, August 7, 2013

weblog; mockito

Mockito

How to Mock Static Methods

     @Test
     public void testGenerateURL() {
          mockStatic( NetworkUtil.class );

          expect( NetworkUtil.getLocalHostname() ).andReturn( "localhost" );
 
          replayAll();
          String results = generator.generateURL();
          verifyAll();

          assertEquals( 
               "http://localhost/myapplication/images/myimage.gif", 
               results );
     }
http://www.michaelminella.com/testing/how-to-mock-static-methods.html

We have all read it or heard someone talk about it. "Static Methods are Death to Testability"... Something that has become a fundimental piece of the language... is so bad that it must be avoided at all costs in the name of testing. [It's] in the language for a reason and to avoid those uses solely because your toolset doesn't support the testing of it is nonsense. Time to get a new toolset.

http://www.michaelminella.com/testing/how-to-mock-static-methods.html

@PrepareForTest can be declared for the entire class or per test method. As would seem, declarations at the test method level override those at the class level.

org.mockito; Annotation Type Spy

01    public class Test{
02    //Instance for spying is created by calling constructor explicitly:
03    @Spy Foo spyOnFoo = new Foo("argument");
04    //Instance for spying is created by mockito via reflection (only default constructors supported):
05    @Spy Bar spyOnBar;
06    @Before
07    public void init(){
08       MockitoAnnotations.initMocks(this);
09    }
10    ...
11 }
http://docs.mockito.googlecode.com/hg/latest/org/mockito/Spy.html

@Spy requires you to initialize the object being spied; it does not seem to use the default constructor as the documentation indicates.

org.mockito; Class Mockito; documentation

http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html

A good place to start learning how to use Mockito. This link supposedly will always return the latest documentation.

How to mock a single method in java

A a = new A();
A aSpy = Mockito.spy(a);
Mockito.when(aSpy.method1()).thenReturn(5l);
http://stackoverflow.com/questions/10895605/how-to-mock-a-single-method-in-java

Or, as documented, in some cases you'd need Mockito.doReturn(51).when(aSpy).method1();. – Arjan Sep 13 '12 at 16:23

http://stackoverflow.com/questions/10895605/how-to-mock-a-single-method-in-java

Mockito; doAnswer()

        doAnswer(new Answer<Void>() {
            public Void answer(InvocationOnMock invocation) {
                ... do stuff ...
            }
        }).when(mockBar).create(any(Foo.class));
http://stackoverflow.com/questions/17244499/testing-method-via-spy-with-mocked-collaborators-using-powermock-mockito

This appears to be a way to provide special handling for the associated stub. It reminds me of how blocks are used with RSpec in the Ruby language.

Important gotcha on spying real objects

   List list = new LinkedList();
   List spy = spy(list);
   
   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
   when(spy.get(0)).thenReturn("foo");
   
   //You have to use doReturn() for stubbing
   doReturn("foo").when(spy).get(0);
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html

Sometimes it's impossible to use when(Object) for stubbing spies.

http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html

Easier mocking with Mockito

http://tutorial.fyicenter.com/out.php?ID=3966

At JTeam we're adopting Mockito in all our new projects. And whenever we have to go back to EasyMock, in the code from earlier projects, we know it was a good move.

http://tutorial.fyicenter.com/out.php?ID=3966

Mockito.LoginServiceExample

package com.om.example.loginservice;
 
import org.junit.Test;
import static org.mockito.Mockito.*;
 
public class LoginServiceTest {
 
   @Test
   public void itShouldSetAccountToLoggedInWhenPasswordMatches() {
      IAccount account = mock(IAccount.class);
      when(account.passwordMatches(anyString())).thenReturn(true);
 
      IAccountRepository accountRepository = mock(IAccountRepository.class);
      when(accountRepository.find(anyString())).thenReturn(account);
 
      LoginService service = new LoginService(accountRepository);
 
      service.login("brett", "password");
 
      verify(account, times(1)).setLoggedIn(true);
   }
}
http://schuchert.wikispaces.com/Mockito.LoginServiceExample http://stackoverflow.com/questions/1404824/learning-resources-for-mockito

This might be a good tutorial to go through; haven't had the time to do so yet. The other link provides references to other tutorials as well.

JUnit and Mockito cooperation

http://fruzenshtein.com/junit-and-mockito/

Mockito framework has conquered my heart. It’s very convenient, its API is clear, usage is laconic."

http://fruzenshtein.com/junit-and-mockito/
ockito framework has conquered my heart. It’s very convenient, its API is clear, usage is laconic."

How to Mock Static Methods

@RunWith( PowerMockRunner.class )
@PrepareForTest( NetworkUtil.class )
public class URLGeneratorTest {
    @Before
     public void setUp() {
          generator = new URLGenerator();
     }

     @Test
     public void testGenerateURL() {
          mockStatic( NetworkUtil.class );

          expect( NetworkUtil.getLocalHostname() ).andReturn( "localhost" );
 
          replayAll();
          String results = generator.generateURL();
          verifyAll();

          assertEquals( 
               "http://localhost/myapplication/images/myimage.gif", 
               results );
     }     
}
http://www.michaelminella.com/testing/how-to-mock-static-methods.html

Mocking static methods (and other "untestable code") is actually quite easy when you put PowerMock to work.

http://www.michaelminella.com/testing/how-to-mock-static-methods.html

Annotation Type PrepareForTest

http://powermock.googlecode.com/svn/docs/powermock-1.3.5/apidocs/org/powermock/core/classloader/annotations/PrepareForTest.html#value%28%29

PrepareForTest() takes either a single class object (e.g., PrepareForTest(MyObject.class) ) or an array of class objects (e.g., PrepareForTest({MyObject.class, AnotherObject.class})

Using PowerMock 1.2.5 with Mockito 1.7

   @PrepareForTest(Static.class); // Static.class contains static methods
   ...

   def testOne{
        //mocks at the class level
        PowerMockito.mockStatic(Static.class);
   }
   ...

   def testTwo{
        //mocks at the time expectations are set up
        Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
   }
http://code.google.com/p/powermock/wiki/MockitoUsage http://code.google.com/p/powermock/wiki/MockitoUsage13

You can set up mocks at the class level or at the time expectations are set up.

EasyMock

Unit testing with JUnit and EasyMock

     public void testRosyScenario() {
          User results = new User();
          String userName = "testUserName";
          String password = "testPassword";
          String passwordHash = 
               "<md5 hash>";
          expect(mockDao.loadByUsernameAndPassword(eq(userName), eq(passwordHash)))
               .andReturn(results);

          replay(mockDao);
          assertTrue(service.login(userName, password));
          verify(mockDao);
     }
http://www.michaelminella.com/testing/unit-testing-with-junit-and-easymock.html

JRuby and RSpec

RSpec for Java

require 'java'
java_import 'Hello'

describe 'Hello' do
  it 'world' do
    Hello.new.world.should == 'world!'
  end
end
http://ujihisa.blogspot.com/2010/09/rspec-for-java.html

Java has some testing frameworks written in Java, but it's difficult to implement something like RSpec due to the limitation of Java syntax.

http://ujihisa.blogspot.com/2010/09/rspec-for-java.html

JtestR

JtestR bundles an old version of RSpec

Keep this in mind when running the Java runner and when you are using JRuby.

No comments:

Post a Comment