本文整理汇总了Java中org.mockito.Mockito.spy方法的典型用法代码示例。如果您正苦于以下问题:Java Mockito.spy方法的具体用法?Java Mockito.spy怎么用?Java Mockito.spy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.mockito.Mockito
的用法示例。
在下文中一共展示了Mockito.spy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: mediaEventOntimeUpdateTestWithTextTrack
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void mediaEventOntimeUpdateTestWithTextTrack() {
// prepare
prepareTextEventMediaWrapper();
Mockito.when(mediaWrapper.getCurrentTime()).thenReturn(5d);
VideoTextTrackElement instance = Mockito.spy(trackElementFactory.getVideoTextTrackElement(TextTrackKind.CAPTIONS));
instance.setMediaDescriptor(mediaWrapper);
instance.init();
// test
eventsBus.fireEventFromSource(event, mediaWrapper, pageScopeFactory.getCurrentPageScope());
event = new MediaEvent(MediaEventTypes.ON_TIME_UPDATE);
eventsBus.fireEventFromSource(event, mediaWrapper, pageScopeFactory.getCurrentPageScope());
verify(instance).onMediaEvent(eq(event));
verify(instance, Mockito.times(2)).showHideText(eq(textTrackCue));
verify(presenter, Mockito.times(2)).setInnerText(eq("test"));
}
示例2: testTransferNotAuthorizationOnWorkbasketTransfer
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test(expected = NotAuthorizedException.class)
public void testTransferNotAuthorizationOnWorkbasketTransfer()
throws Exception {
String destinationWorkbasketKey = "2";
Task task = createUnitTestTask("1", "Unit Test Task 1", "1");
TaskServiceImpl cutSpy = Mockito.spy(cut);
doReturn(task).when(cutSpy).getTask(task.getId());
doNothing().when(workbasketServiceMock).checkAuthorization(destinationWorkbasketKey,
WorkbasketAuthorization.APPEND);
doThrow(NotAuthorizedException.class).when(workbasketServiceMock).checkAuthorization(task.getWorkbasketKey(),
WorkbasketAuthorization.TRANSFER);
try {
cutSpy.transfer(task.getId(), destinationWorkbasketKey);
} catch (Exception e) {
verify(taskanaEngineImpl, times(1)).openConnection();
verify(workbasketServiceMock, times(1)).checkAuthorization(destinationWorkbasketKey,
WorkbasketAuthorization.APPEND);
verify(workbasketServiceMock, times(1)).checkAuthorization(task.getWorkbasketKey(),
WorkbasketAuthorization.TRANSFER);
verify(taskanaEngineImpl, times(1)).returnConnection();
verifyNoMoreInteractions(attachmentMapperMock, taskanaEngineConfigurationMock, taskanaEngineMock,
taskanaEngineImpl, taskMapperMock, objectReferenceMapperMock, workbasketServiceMock);
throw e;
}
}
示例3: mockedWithSpy
import org.mockito.Mockito; //导入方法依赖的package包/类
/**
* A spy in mockito is a partial mock in other mocking frameworks
* (part of the object will be mocked and part will use real method invocations).
*/
@Test
public void mockedWithSpy() {
EmailsReader emailsReader = Mockito.mock(EmailsReader.class);
LotteryMachine lotteryMachine = new LotteryMachine(5);
LotteryMachine spyMachine = Mockito.spy(lotteryMachine);
String seedString = "Test";
long longSeed = 1L;
when(spyMachine.getSeed()).thenReturn(longSeed);
Lottery lottery = new Lottery(emailsReader, spyMachine, seedString);
lottery.run();
Assert.assertEquals(LotteryMachine.DEFAULT_SEED, lotteryMachine.getSeed());
Assert.assertEquals(longSeed, spyMachine.getSeed()); //not to seedString.hashCode();
}
示例4: invalidJsonForDiscoveryFilter
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void invalidJsonForDiscoveryFilter() throws CmdLineException, ConfigurationException {
OFEventWFMTopology manager = new OFEventWFMTopology(makeLaunchEnvironment());
TopologyConfig config = manager.getConfig();
OFELinkBolt bolt = new OFELinkBolt(config);
TopologyContext context = Mockito.mock(TopologyContext.class);
Mockito.when(context.getComponentId(TASK_ID_BOLT))
.thenReturn(COMPONENT_ID_SOURCE);
Mockito.when(context.getComponentOutputFields(COMPONENT_ID_SOURCE, STREAM_ID_INPUT))
.thenReturn(KafkaMessage.FORMAT);
OutputCollectorMock outputDelegate = Mockito.spy(new OutputCollectorMock());
OutputCollector output = new OutputCollector(outputDelegate);
bolt.prepare(stormConfig(), context, output);
bolt.initState(new InMemoryKeyValueState<>());
Tuple tuple = new TupleImpl(context, new Values("{\"corrupted-json"), TASK_ID_BOLT, STREAM_ID_INPUT);
bolt.doWork(tuple);
Mockito.verify(outputDelegate).ack(tuple);
}
示例5: MemcachedClientException
import org.mockito.Mockito; //导入方法依赖的package包/类
/**
* getメソッドでMemcachedへの接続に失敗した場合NULLを返すこと.
* @throws Exception テスト中の例外
*/
@SuppressWarnings("unchecked")
@Test
public void getメソッドでMemcachedへの接続に失敗した場合NULLを返すこと() throws Exception {
String nodeId = "nodeId";
// MemcachedClientのモックを作成(getしたときにMemchachedClientExceptionをthrowするモック)
Constructor<MemcachedClient> c = MemcachedClient.class.getDeclaredConstructor();
c.setAccessible(true);
MemcachedClient mockMemcachedClient = Mockito.spy(c.newInstance());
Mockito.doThrow(new MemcachedClientException(null)).when(mockMemcachedClient)
.get(Mockito.anyString(), Mockito.any(Class.class));
// UserDataSchemaCacheのモックを作成(MemcachedClientのモックを使用するモック)
PowerMockito.spy(UserDataSchemaCache.class);
PowerMockito.when(UserDataSchemaCache.class, "getMcdClient").thenReturn(mockMemcachedClient);
// キャッシュの設定を有効にする
PowerMockito.spy(PersoniumUnitConfig.class);
PowerMockito.when(PersoniumUnitConfig.class, "isSchemaCacheEnabled").thenReturn(true);
// getメソッドのテスト
Map<String, Object> cache = UserDataSchemaCache.get(nodeId);
assertNull(cache);
}
示例6: createAListener
import org.mockito.Mockito; //导入方法依赖的package包/类
private synchronized Pair<Integer, RESTUpdateUserInfo.Listener> createAListener() {
final Integer index = isOperationCompleteList.size();
isOperationCompleteList.add(false);
RESTUpdateUserInfo.Listener listener = Mockito.spy(new RESTUpdateUserInfo.Listener() {
@Override
public void onSuccess() {
isOperationCompleteList.set(index, true);
}
@Override
public void onFailure(String errMsg) {
isOperationCompleteList.set(index, true);
}
});
return new Pair<>(index, listener);
}
示例7: setup
import org.mockito.Mockito; //导入方法依赖的package包/类
@Before
public void setup() throws Exception {
ledger = new Ledger();
backlog = new Backlog();
Storage mockStorage = mock(Storage.class);
when(mockStorage.getBacklog()).thenReturn(backlog);
service = Mockito.spy(new AccountService(mockStorage));
doAnswer(new Answer<IAccount>() {
@Override
public IAccount answer(InvocationOnMock invocation) throws Throwable {
long id = Format.ID.accountId(invocation.getArgument(0));
return ledger.getAccount(id);
}
}).when(service).getAccount(anyString());
Ed25519SignatureVerifier signatureVerifier = new Ed25519SignatureVerifier();
CryptoProvider cryptoProvider = new CryptoProvider(new SignedObjectMapper(0L));
cryptoProvider.addProvider(signatureVerifier);
cryptoProvider.setDefaultProvider(signatureVerifier.getName());
CryptoProvider.init(cryptoProvider);
}
示例8: scanSingleResult
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void scanSingleResult() throws Exception {
final DatagramSocket socketMessage = mock(DatagramSocket.class);
doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(any(DatagramPacket.class));
FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
SSDPDiscovery ssdp = new SSDPDiscovery("urn:cast-ocast-org:service:cast:1", 3000) {
@Override
protected DatagramSocket createSocket() {
return socketMessage;
}
};
ssdp.addListener(callback);
ssdp.start();
callback.await(3, TimeUnit.SECONDS);
verify(callback, times(1)).onLocationSent();
verify(callback, times(1)).onLocationReceived(any(SSDPMessage.class));
SSDPMessage result = callback.getResult();
assertThat(result.getUuid(), is(equalTo("c4323fee-db4b-4227-9039-fa4b71589e26")));
}
示例9: runGoodMessageRaw
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void runGoodMessageRaw() throws Exception {
setupRawData(false);
KafkaRpcPluginThread writer = Mockito.spy(
new KafkaRpcPluginThread(group, 1, TOPICS));
writer.run();
verifyMessageRead(writer, false);
verify(tsdb, times(1)).addPoint(METRIC, TS, 42L, TAGS);
verifyCtrsInc(new String[]{ "readRawCounter", "storedRawCounter" });
}
示例10: testIsValidNameInvalidInBaseFs
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void testIsValidNameInvalidInBaseFs() throws Exception {
AbstractFileSystem baseFs = Mockito.spy(fc.getDefaultFileSystem());
ChRootedFs chRootedFs = new ChRootedFs(baseFs, new Path("/chroot"));
Mockito.doReturn(false).when(baseFs).isValidName(Mockito.anyString());
Assert.assertFalse(chRootedFs.isValidName("/test"));
Mockito.verify(baseFs).isValidName("/chroot/test");
}
示例11: testProcessPartialRequestWithoutCache
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void testProcessPartialRequestWithoutCache() throws Exception {
FileCache fileCache = new FileCache(ProxyCacheTestUtils.newCacheFile());
FileCache spyFileCache = Mockito.spy(fileCache);
doThrow(new RuntimeException()).when(spyFileCache).read(any(byte[].class), anyLong(), anyInt());
String httpRequest = "GET /" + HTTP_DATA_URL + " HTTP/1.1\nRange: bytes=2000-";
Response response = processRequest(HTTP_DATA_URL, httpRequest, spyFileCache);
byte[] fullData = loadTestData();
byte[] partialData = new byte[fullData.length - 2000];
System.arraycopy(fullData, 2000, partialData, 0, partialData.length);
assertThat(response.data).isEqualTo(partialData);
assertThat(response.code).isEqualTo(206);
}
示例12: testTransferTaskToDestinationWorkbasketWithoutSecurity
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void testTransferTaskToDestinationWorkbasketWithoutSecurity()
throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException,
ClassificationAlreadyExistException, InvalidWorkbasketException, ClassificationNotFoundException {
TaskServiceImpl cutSpy = Mockito.spy(cut);
Workbasket destinationWorkbasket = createWorkbasket("2", "k1");
TaskImpl task = createUnitTestTask("1", "Unit Test Task 1", "k1");
task.setRead(true);
doReturn(destinationWorkbasket).when(workbasketServiceMock).getWorkbasketByKey(destinationWorkbasket.getKey());
doReturn(taskanaEngineConfigurationMock).when(taskanaEngineMock).getConfiguration();
doReturn(false).when(taskanaEngineConfigurationMock).isSecurityEnabled();
doReturn(task).when(cutSpy).getTask(task.getId());
doNothing().when(taskMapperMock).update(any());
doNothing().when(workbasketServiceMock).checkAuthorization(destinationWorkbasket.getKey(),
WorkbasketAuthorization.APPEND);
doNothing().when(workbasketServiceMock).checkAuthorization(task.getWorkbasketKey(),
WorkbasketAuthorization.TRANSFER);
Task actualTask = cutSpy.transfer(task.getId(), destinationWorkbasket.getKey());
verify(taskanaEngineImpl, times(1)).openConnection();
verify(workbasketServiceMock, times(1)).checkAuthorization(destinationWorkbasket.getKey(),
WorkbasketAuthorization.APPEND);
verify(workbasketServiceMock, times(1)).checkAuthorization(task.getWorkbasketKey(),
WorkbasketAuthorization.TRANSFER);
verify(taskanaEngineMock, times(1)).getConfiguration();
verify(taskanaEngineConfigurationMock, times(1)).isSecurityEnabled();
verify(workbasketServiceMock, times(2)).getWorkbasketByKey(destinationWorkbasket.getKey());
verify(taskMapperMock, times(1)).update(any());
verify(taskanaEngineImpl, times(1)).returnConnection();
verifyNoMoreInteractions(attachmentMapperMock, taskanaEngineConfigurationMock, taskanaEngineMock,
taskanaEngineImpl, taskMapperMock, objectReferenceMapperMock, workbasketServiceMock);
assertThat(actualTask.isRead(), equalTo(false));
assertThat(actualTask.isTransferred(), equalTo(true));
assertThat(actualTask.getWorkbasketKey(), equalTo(destinationWorkbasket.getKey()));
}
示例13: testLoad_FileLengthis0FilesExistsSecondTimeAroundSuccess
import org.mockito.Mockito; //导入方法依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testLoad_FileLengthis0FilesExistsSecondTimeAroundSuccess() throws Exception {
Class configClass = JsonConfig.class;
File mockFile = PowerMockito.mock(File.class);
FileWriter mockFileWriter = PowerMockito.mock(FileWriter.class);
FileWriter spyFileWriter = Mockito.spy(mockFileWriter);
Mockito.when(mockFile.exists()).thenReturn(true);
Mockito.when(mockFile.length()).thenReturn(0l);
PowerMockito.whenNew(FileWriter.class).withParameterTypes(File.class).withArguments(mockFile).thenReturn(mockFileWriter);
Mockito.when(mockFile.getParentFile()).thenReturn(null);
Mockito.when(mockFile.exists()).thenReturn(true);
Mockito.doNothing().when(spyFileWriter).write(Mockito.anyString());
Mockito.doNothing().when(spyFileWriter).close();
JsonConfig response = JsonConfig.load(mockFile, configClass);
assertThat(response).isNotNull();
Mockito.verify(mockFile, Mockito.times(2)).exists();
Mockito.verify(mockFile, Mockito.times(1)).length();
PowerMockito.verifyNew(FileWriter.class, Mockito.times(1)).withArguments(Mockito.isA(File.class));
Mockito.verify(mockFile, Mockito.times(1)).getParentFile();
Mockito.verify(mockFileWriter, Mockito.times(1)).write(Mockito.anyString());
Mockito.verify(mockFileWriter, Mockito.times(2)).close();
}
示例14: translationInterceptor
import org.mockito.Mockito; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void translationInterceptor() {
JpaEntityRepository<TestEntity, Long> repo = new JpaEntityRepository<>(module, JpaRepositoryConfig.create(TestEntity.class));
QuerydslRepositoryFilterBase filter = Mockito.spy(new QuerydslRepositoryFilterBase());
module.addFilter(filter);
QuerySpec querySpec = new QuerySpec(TestEntity.class);
repo.findAll(querySpec);
Mockito.verify(filter, Mockito.times(1)).filterQueryTranslation(Mockito.eq(repo), Mockito.eq(querySpec),
Mockito.any(QuerydslTranslationContext.class));
}
示例15: testPresenterLifeCycleIsRespectedOnStop
import org.mockito.Mockito; //导入方法依赖的package包/类
@Test
public void testPresenterLifeCycleIsRespectedOnStop()
{
final Presenter presenter = Mockito.spy(Presenter.class);
final ActivityTest activity = Mockito.spy(new ActivityTest());
activity.onLoadFinished(null, presenter);
activity.onStart();
activity.onStop();
// Verify onStop and onViewDetached are called in right order
final InOrder inOrder = Mockito.inOrder(presenter);
inOrder.verify(presenter).onStop();
inOrder.verify(presenter).onViewDetached();
}