- powermock-mockito:1.4.11
- 模拟:1.9.0
- 播放:1.2.3
我正在尝试使用 powermock-mockito 模拟最后一堂课。为此,您必须使用 @RunWith(PowerMockRunner) - 注释来注释测试的类。但是 - 我想 - 这似乎混淆了我自己测试的类 DropboxCrawlerTests 导致 ClassNotFoundException 的游戏:
A java.lang.ClassNotFoundException has been caught, mashpan.crawl.dropbox.DropboxCrawlerTests
DropboxCrawlerTests.java:
@RunWith(PowerMockRunner.class)
@PrepareForTest(XContentBuilder.class)
public class DropboxCrawlerTests extends UnitTest {
@Before
public void setUp() {
Fixtures.deleteDatabase();
Fixtures.loadModels("testusers.yaml");
Cache.clear();
}
..
}
编辑:
完整的堆栈跟踪:
java.lang.ClassNotFoundException: mashpan.crawl.dropbox.DropboxCrawlerMultipleFilesTests
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:143)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:65)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:133)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:39)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:217)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.(JUnit4TestSuiteChunkerImpl.java:59)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.(AbstractCommonPowerMockRunner.java:32)
at org.powermock.modules.junit4.PowerMockRunner.(PowerMockRunner.java:31)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runner.Computer.getRunner(Computer.java:38)
at org.junit.runner.Computer$1.runnerForClass(Computer.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:93)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:84)
at org.junit.runners.Suite.(Suite.java:79)
at org.junit.runner.Computer.getSuite(Computer.java:26)
at org.junit.runner.Request.classes(Request.java:69)
at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
at play.test.TestEngine.run(TestEngine.java:101)
at controllers.TestRunner.run(TestRunner.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:546)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:500)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:476)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:471)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:159)
at play.server.PlayHandler$NettyInvocation.execute(PlayHandler.java:220)
at play.Invoker$Invocation.run(Invoker.java:265)
at play.server.PlayHandler$NettyInvocation.run(PlayHandler.java:200)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:165)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
EDIT2:这就是我要模拟的类: http: //semicomplete.com/doc/org/elasticsearch/common/xcontent/XContentBuilder.html
编辑3:
用于测试 DropboxCrawlerTests.java 的基类
package mashpan.crawl.dropbox;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mashpan.index.ElasticSearch;
import mashpan.index.ServiceIndexes;
import mashpan.mailer.Mailer;
import mashpan.monitoring.ExceptionMonitor;
import mashpan.security.PBE;
import mashpan.utilities.UserUtility;
import models.DropboxAuthentication;
import models.DropboxFolder;
import models.User;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.action.bulk.BulkRequestBuilder;
import org.elasticsearch.client.action.index.IndexRequestBuilder;
import org.elasticsearch.common.xcontent.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.*;
import org.mockito.internal.verification.Times;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.junit4.*;
import play.Logger;
import play.cache.Cache;
import play.test.Fixtures;
import play.test.UnitTest;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.WebAuthSession;
@RunWith(PowerMockRunner.class)
@PrepareForTest(XContentBuilder.class)
public class DropboxCrawlerTests extends UnitTest {
@Before
public void setUp() {
Fixtures.deleteDatabase();
Fixtures.loadModels("testusers.yaml");
Cache.clear();
}
/*************** HELPERS ***************************/
// example how to construct a real dropboxauthentication object
protected DropboxAuthentication createDefaultDropboxAuthentication(User user) {
PBE pbe = new PBE("deroom1234".toCharArray());
String secret = UserUtility.DROPBOXSECRET;
String token = UserUtility.DROPBOXTOKEN;
HashMap<String, byte[]> encrypted = pbe.encrypt(secret.getBytes());
return new DropboxAuthentication(
"document"
, encrypted.get("cypher")
, encrypted.get("iv")
, token
, secret
, user
, new Date());
}
@SuppressWarnings("unused")
private DropboxCrawler createDefaultDropboxCrawler() throws DropboxException, IOException {
User user = User.find("byEmail", UserUtility.EMAIL).first();
DropboxAuthentication dropboxAuthentication = mock(DropboxAuthentication.class);
dropboxAuthentication.user = user;
Mailer mailer = mock(Mailer.class);
ServiceIndexes indexer = mock(ServiceIndexes.class);
XContentBuilder jsonBuilder = createJsonBuilder();
ElasticSearch elasticsearch = createElasticSearchMock(jsonBuilder);
DropboxConnector dropboxConnector = createDropboxConnector(dropboxAuthentication);
Logger.debug("[DropboxCrawlerTests] dropboxAuthentication.user="+user);
ExceptionMonitor exceptionMonitor = mock(ExceptionMonitor.class);
return new DropboxCrawler(user.email
, dropboxAuthentication
, mailer
, indexer
, elasticsearch
, dropboxConnector
, exceptionMonitor
, jsonBuilder);
}
protected DropboxConnector createDropboxConnector(DropboxAuthentication dropboxAuthentication) throws DropboxException {
String hash = "hash";
Entry entry = mock(Entry.class);
entry.hash = hash;
entry.contents = new ArrayList<DropboxAPI.Entry>();
DropboxAPI<WebAuthSession> dropboxAPI = mock(DropboxAPI.class);
when(dropboxAPI.metadata("/", 0, null, true, null)).thenReturn(entry);
DropboxConnector dropboxConnector = mock(DropboxConnector.class);
when(dropboxConnector.connect(dropboxAuthentication)).thenReturn(dropboxAPI);
return dropboxConnector;
}
protected XContentBuilder createJsonBuilder() throws IOException {
XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
// Class<? extends XContentBuilder> class1 = XContentFactory.jsonBuilder().getClass();
// Logger.debug("[DropboxCrawlerTests] class="+class1);
// XContentBuilder jsonBuilder = mock(class1);
// when(jsonBuilder.startObject()).thenReturn(jsonBuilder);
// when(jsonBuilder.field(any(String.class), any(String.class))).thenReturn(jsonBuilder);
// when(jsonBuilder.endObject()).thenReturn(jsonBuilder);
// return jsonBuilder;
return jsonBuilder;
}
protected ElasticSearch createElasticSearchMock(XContentBuilder jsonBuilder) {
IndexRequestBuilder indexRequestBuilder = mock(IndexRequestBuilder.class);
when(indexRequestBuilder.setSource(jsonBuilder)).thenReturn(indexRequestBuilder);
Client client = mock(Client.class);
when(client.prepareIndex("dropbox", "documents")).thenReturn(indexRequestBuilder);
BulkResponse bulkResponse = mock(BulkResponse.class);
when(bulkResponse.hasFailures()).thenReturn(false);
ListenableActionFuture actionFuture = mock(ListenableActionFuture.class);
when(actionFuture.actionGet()).thenReturn(bulkResponse);
BulkRequestBuilder bulkRequestBuilder = mock(BulkRequestBuilder.class);
when(bulkRequestBuilder.execute()).thenReturn(actionFuture);
ElasticSearch elasticsearch = mock(ElasticSearch.class);
when(elasticsearch.getClient()).thenReturn(client);
when(elasticsearch.newBulkRequest()).thenReturn(bulkRequestBuilder);
return elasticsearch;
}
}
实际测试类 DropboxCrawlMultipleFilesTests.java
package mashpan.crawl.dropbox;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.io.*;
import java.util.*;
import mashpan.crawl.main.*;
import mashpan.document.*;
import mashpan.index.ElasticSearch;
import mashpan.index.ServiceIndexes;
import mashpan.mailer.Mailer;
import mashpan.monitoring.ExceptionMonitor;
import mashpan.utilities.UserUtility;
import models.DropboxAuthentication;
import models.User;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.action.bulk.BulkRequestBuilder;
import org.elasticsearch.client.action.index.IndexRequestBuilder;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.junit.*;
import org.junit.runner.*;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.junit4.*;
import play.Logger;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.WebAuthSession;
public class DropboxCrawlerCrawlMultipleFilesTests extends DropboxCrawlerTests {
/*************** Multiple Files+Folders ***********************/
/**
*
*/
@Test
@Ignore
public void crawl_multipleFiles_shouldSetFieldsForJsonBuilder() throws DropboxException, IOException {
Logger.debug("[DropboxCrawlerTests] crawl_singleFolder_shouldAddItemsToBulkRequest");
User user = User.find("byEmail", UserUtility.EMAIL).first();
DropboxAuthentication dropboxAuthentication = createDefaultDropboxAuthentication(user);
Mailer mailer = mock(Mailer.class);
ServiceIndexes indexer = mock(ServiceIndexes.class);
XContentBuilder jsonBuilder = createJsonBuilder();
IndexRequestBuilder indexRequestBuilder = mock(IndexRequestBuilder.class);
when(indexRequestBuilder.setSource(jsonBuilder)).thenReturn(indexRequestBuilder);
Client client = mock(Client.class);
when(client.prepareIndex("dropbox", "documents")).thenReturn(indexRequestBuilder);
BulkResponse bulkResponse = mock(BulkResponse.class);
when(bulkResponse.hasFailures()).thenReturn(false);
ListenableActionFuture actionFuture = mock(ListenableActionFuture.class);
when(actionFuture.actionGet()).thenReturn(bulkResponse);
BulkRequestBuilder bulkRequestBuilder = mock(BulkRequestBuilder.class);
when(bulkRequestBuilder.execute()).thenReturn(actionFuture);
ElasticSearch elasticsearch = mock(ElasticSearch.class);
when(elasticsearch.getClient()).thenReturn(client);
when(elasticsearch.newBulkRequest()).thenReturn(bulkRequestBuilder);
Entry rootDir = mock(Entry.class);
String rootHash = "hash";
rootDir.hash = rootHash;
rootDir.isDir = true;
rootDir.contents = new ArrayList<DropboxAPI.Entry>();
Entry subDir1 = mock(Entry.class);
String subDir1Hash = "subDirHash";
subDir1.hash = subDir1Hash;
subDir1.isDir = true;
subDir1.path = "subDir1";
subDir1.contents = new ArrayList<DropboxAPI.Entry>();
rootDir.contents.add(subDir1);
Entry file1 = mock(Entry.class);
String file1Hash = "file1Hash";
file1.hash = file1Hash;
file1.isDir = false;
file1.contents = new ArrayList<DropboxAPI.Entry>();
file1.modified = "12/06/2012"; //EEE, dd MMM yyyy kk:mm:ss ZZZZZ https://www.dropbox.com/static/developers/dropbox-java-sdk-1.2.3-docs/com/dropbox/client2/DropboxAPI.Entry.html#modified
file1.mimeType = "text/html";
file1.rev = "file1";
file1.path = subDir1.path+"/"+file1.rev;
subDir1.contents.add(file1);
Entry file2 = mock(Entry.class);
String file2Hash = "file2Hash";
file2.hash = file2Hash;
file2.isDir = false;
file2.contents = new ArrayList<DropboxAPI.Entry>();
file2.modified = "12/06/2012"; //EEE, dd MMM yyyy kk:mm:ss ZZZZZ https://www.dropbox.com/static/developers/dropbox-java-sdk-1.2.3-docs/com/dropbox/client2/DropboxAPI.Entry.html#modified
file2.mimeType = "text/html";
file2.rev = "file2";
file2.path = subDir1.path+"/"+file2.rev;
subDir1.contents.add(file2);
Entry subDir2 = mock(Entry.class);
String subDirHash2 = "subDirHash2";
subDir2.hash = subDirHash2;
subDir2.isDir = true;
subDir2.contents = new ArrayList<DropboxAPI.Entry>();
rootDir.contents.add(subDir2);
DropboxAPI<WebAuthSession> dropboxAPI = mock(DropboxAPI.class);
when(dropboxAPI.metadata("/", 0, null, true, null)).thenReturn(rootDir);
DropboxConnector dropboxConnector = mock(DropboxConnector.class);
when(dropboxConnector.connect(dropboxAuthentication)).thenReturn(dropboxAPI);
ExceptionMonitor exceptionMonitor = mock(ExceptionMonitor.class);
new DropboxCrawler(user.email
, dropboxAuthentication
, mailer
, indexer
, elasticsearch
, dropboxConnector
, exceptionMonitor
, jsonBuilder)
.crawl();
fail();
//TODO comment in
// verifyJsonBuilder(user, jsonBuilder, file1);
// verifyJsonBuilder(user, jsonBuilder, file2);
}
@Test
// @Ignore
public void crawl_multipleFiles_bulkRequestBuilder() throws DropboxException, IOException {
Logger.debug("[DropboxCrawlerTests] crawl_singleFolder_shouldAddItemsToBulkRequest");
User user = User.find("byEmail", UserUtility.EMAIL).first();
DropboxAuthentication dropboxAuthentication = createDefaultDropboxAuthentication(user);
Mailer mailer = mock(Mailer.class);
ServiceIndexes indexer = mock(ServiceIndexes.class);
XContentBuilder jsonBuilder = createJsonBuilder();
IndexRequestBuilder indexRequestBuilder = mock(IndexRequestBuilder.class);
when(indexRequestBuilder.setSource(jsonBuilder)).thenReturn(indexRequestBuilder);
Client client = mock(Client.class);
when(client.prepareIndex("dropbox", "documents")).thenReturn(indexRequestBuilder);
BulkResponse bulkResponse = mock(BulkResponse.class);
when(bulkResponse.hasFailures()).thenReturn(false);
ListenableActionFuture actionFuture = mock(ListenableActionFuture.class);
when(actionFuture.actionGet()).thenReturn(bulkResponse);
BulkRequestBuilder bulkRequestBuilder = mock(BulkRequestBuilder.class);
when(bulkRequestBuilder.execute()).thenReturn(actionFuture);
ElasticSearch elasticsearch = mock(ElasticSearch.class);
when(elasticsearch.getClient()).thenReturn(client);
when(elasticsearch.newBulkRequest()).thenReturn(bulkRequestBuilder);
Entry rootDir = mock(Entry.class);
String rootHash = "hash";
rootDir.hash = rootHash;
rootDir.isDir = true;
rootDir.contents = new ArrayList<DropboxAPI.Entry>();
Entry subDir1 = mock(Entry.class);
String subDir1Hash = "subDirHash";
subDir1.hash = subDir1Hash;
subDir1.isDir = true;
subDir1.path = "subDir1";
subDir1.contents = new ArrayList<DropboxAPI.Entry>();
rootDir.contents.add(subDir1);
String file1Hash = "dFile1Hash";
String file1Rev = "dFile1Rev";
Entry file1 = new Entry(createEntryMap(
file1Hash
, false
, 4392763
, "12/06/2012"
, subDir1.path+"/"+file1Rev
, false
, "4.2MB"
, null
, null
, "page_white_compressed"
));
subDir1.contents.add(file1);
String file2Hash = "dFile2Hash";
String file2Rev = "dFile2Rev";
Entry file2 = new Entry(createEntryMap(
file2Hash
, false
, 4392763
, "12/06/2012"
, subDir1.path+"/"+file2Rev
, false
, "4.2MB"
, null
, null
, "page_white_compressed"
));
subDir1.contents.add(file2);
Entry subDir2 = mock(Entry.class);
String subDirHash2 = "subDirHash2";
subDir2.hash = subDirHash2;
subDir2.isDir = true;
subDir2.contents = new ArrayList<DropboxAPI.Entry>();
rootDir.contents.add(subDir2);
DropboxAPI<WebAuthSession> dropboxAPI = mock(DropboxAPI.class);
when(dropboxAPI.metadata("/", 0, null, true, null)).thenReturn(rootDir);
when(dropboxAPI.metadata(subDir1.path, 0, null, true, null)).thenReturn(subDir1);
when(dropboxAPI.metadata(subDir2.path, 0, null, true, null)).thenReturn(subDir2);
DropboxConnector dropboxConnector = mock(DropboxConnector.class);
when(dropboxConnector.connect(dropboxAuthentication)).thenReturn(dropboxAPI);
ExceptionMonitor exceptionMonitor = mock(ExceptionMonitor.class);
new DropboxCrawler(user.email
, dropboxAuthentication
, mailer
, indexer
, elasticsearch
, dropboxConnector
, exceptionMonitor
, jsonBuilder)
.crawl();
verify(bulkRequestBuilder, times(2)).add(indexRequestBuilder);
//TODO comment in
// verifyJsonBuilder(user, jsonBuilder, file1);
// verifyJsonBuilder(user, jsonBuilder, file2);
}
private HashMap<String,Object> createEntryMap(
Object hash
, Object thumb_exists
, Object bytes
, Object modified
, Object path
, Object is_dir
, Object size
, Object root
, Object contents
, Object icon) {
HashMap<String, Object> map = new HashMap<String, Object>();
if(hash != null)
map.put("hash", hash);
map.put("thumb_exists", thumb_exists);
map.put("bytes", bytes);
map.put("modified", modified);
map.put("path", path);
map.put("is_dir", is_dir);
map.put("size", size);
if(root != null)
map.put("root", root);
if(contents != null)
map.put("contents", contents);
if(icon != null)
map.put("icon", icon);
return map;
}
@SuppressWarnings("unused")
private void verifyJsonBuilder(User user, XContentBuilder jsonBuilder,
Entry file) throws IOException {
verify(jsonBuilder).field("user", user.email);
verify(jsonBuilder).field("type", "document");
verify(jsonBuilder).field("mimetype", file.mimeType);
verify(jsonBuilder).field("filename", Utils.dropExtension(file.fileName()));
verify(jsonBuilder).field("revision", file.rev);
String path = file.path.replaceAll("/", "");
path = Utils.dropExtension(path);
verify(jsonBuilder).field("path", path);
verify(jsonBuilder).field("fullpath", file.path);
}
}