In
this post, I am going to explain how to create mock object and how to mock the
methods of the mocked object.
By
using PowerMock class 'createMock' method we can create a mock object. Once the
mock object is created, we can set expectations to the methods.
Following
snippet, create mock object for File class, and set expectations to the methods
'getName', 'getAbsolutePath’.
File file =
PowerMock.createMock(File.class);
EasyMock.expect(file.getName()).andReturn("TestFile");
EasyMock.expect(file.getAbsolutePath()).andReturn("/Users/HariKrishna/TestFile");
PowerMock.replayAll();
Following
is the complete working application.
Test.java
package com.sample.tests; import java.io.File; import org.easymock.EasyMock; import org.powermock.api.easymock.PowerMock; public class Test { public static void main(String args[]){ File file = PowerMock.createMock(File.class); EasyMock.expect(file.getName()).andReturn("TestFile"); EasyMock.expect(file.getAbsolutePath()).andReturn("/Users/HariKrishna/TestFile"); PowerMock.replayAll(); System.out.println(file.getName()); System.out.println(file.getAbsolutePath()); } }
No comments:
Post a Comment