7

Is it possible to mock a concrete class using EaskMock? If so, how do I do it?

senfo
  • 28,488
  • 15
  • 76
  • 106
Samuel Carrijo
  • 17,449
  • 12
  • 49
  • 59

6 Answers6

11

See the EasyMock Class Extension documentation and download it from the SourceForge project. You can't mock final methods though.

EDIT: This is now part of EasyMock for v3 and above, as noted in comments.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    It should be noted that the new versions of EasyMock (>= 3.0) include this extension, as Mike Partridge noted in another answer here. – Zoltán Apr 02 '14 at 09:11
7

Powermock extends EasyMock and allows you to mock concrete types, even final and static methods.

PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.

Rich Seller
  • 83,208
  • 23
  • 172
  • 177
3

Yes: http://easymock.org/EasyMock2_4_ClassExtension_Documentation.html

jqno
  • 15,133
  • 7
  • 57
  • 84
3

EasyMock class extensions have been integrated into EasyMock as of v3.0; see the release notes.

Mike Partridge
  • 5,128
  • 8
  • 35
  • 47
0

When creating a mock, simply use the org.easymock.classextension version of the EasyMock class. The result will be castable.

Here's a recent link - http://easymock.org/EasyMock3_2_ClassExtension_Documentation.html

Jay Bose
  • 1,511
  • 2
  • 11
  • 14
0

You can mock an object using 'PowerMock.createMock' method. Reference link.

Example

File file = PowerMock.createMock(File.class);
                
EasyMock.expect(file.getName()).andReturn("TestFile");
EasyMock.expect(file.getAbsolutePath()).andReturn("/Users/HariKrishna/TestFile");

If you want to partially mock some of the methods, you can use 'PowerMock.createPartialMock' method. Reference link.

Example

EmployeeService empService = PowerMock.createPartialMock(EmployeeService.class, "getEmployeeFirstNames");
EasyMock.expect(empService.getEmployeeFirstNames(emps)).andReturn(empNames);

Refer this tutorial for more examples.

Hari Krishna
  • 3,658
  • 1
  • 36
  • 57