org.mockito.MockSettings类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(17.5k)|赞(0)|评价(0)|浏览(82)

本文整理了Java中org.mockito.MockSettings类的一些代码示例,展示了MockSettings类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MockSettings类的具体详情如下:
包路径:org.mockito.MockSettings
类名称:MockSettings

MockSettings介绍

[英]Allows mock creation with additional mock settings.

Don't use it too often. Consider writing simple tests that use simple mocks. Repeat after me: simple tests push simple, KISSy, readable & maintainable code. If you cannot write a test in a simple way - refactor the code under test.

Examples of mock settings:

//Creates mock with different default answer & name 
Foo mock = mock(Foo.class, withSettings() 
.defaultAnswer(RETURNS_SMART_NULLS) 
.name("cool mockie") 
); 
//Creates mock with different default answer, descriptive name and extra interfaces 
Foo mock = mock(Foo.class, withSettings() 
.defaultAnswer(RETURNS_SMART_NULLS) 
.name("cool mockie") 
.extraInterfaces(Bar.class));

MockSettings has been introduced for two reasons. Firstly, to make it easy to add another mock setting when the demand comes. Secondly, to enable combining together different mock settings without introducing zillions of overloaded mock() methods.
[中]允许使用其他模拟设置创建模拟。
不要经常使用它。考虑编写使用简单模拟的简单测试。跟着我重复:简单的测试推送简单、轻吻、可读和可维护的代码。如果你不能用一种简单的方式编写一个测试,重构测试代码。
模拟设置示例:

//Creates mock with different default answer & name 
Foo mock = mock(Foo.class, withSettings() 
.defaultAnswer(RETURNS_SMART_NULLS) 
.name("cool mockie") 
); 
//Creates mock with different default answer, descriptive name and extra interfaces 
Foo mock = mock(Foo.class, withSettings() 
.defaultAnswer(RETURNS_SMART_NULLS) 
.name("cool mockie") 
.extraInterfaces(Bar.class));

引入MockSettings有两个原因。首先,为了方便在需求到来时添加另一个模拟设置。第二,在不引入大量重载mock()方法的情况下,允许组合不同的mock设置。

代码示例

代码示例来源:origin: CalebFenton/simplify

private static ExecutionGraphManipulator getMockedGraph(int address, HeapItem value) {
  ExecutionGraphManipulator manipulator = mock(ExecutionGraphManipulator.class);
  BuilderInstruction instruction =
      mock(BuilderInstruction.class, withSettings().extraInterfaces(OneRegisterInstruction.class));
  when(((OneRegisterInstruction) instruction).getRegisterA()).thenReturn(REGISTER);
  when(manipulator.getRegisterConsensus(address, REGISTER)).thenReturn(value);
  when(manipulator.getInstruction(address)).thenReturn(instruction);
  return manipulator;
}

代码示例来源:origin: org.mockito/mockito-core

private static Object spyInstance(Field field, Object instance) {
  return Mockito.mock(instance.getClass(),
            withSettings().spiedInstance(instance)
                            .defaultAnswer(CALLS_REAL_METHODS)
                            .name(field.getName()));
}

代码示例来源:origin: org.mockito/mockito-core

public static Object processAnnotationForMock(Mock annotation, Class<?> type, String name) {
    MockSettings mockSettings = Mockito.withSettings();
    if (annotation.extraInterfaces().length > 0) { // never null
      mockSettings.extraInterfaces(annotation.extraInterfaces());
    }
    if ("".equals(annotation.name())) {
      mockSettings.name(name);
    } else {
      mockSettings.name(annotation.name());
    }
    if(annotation.serializable()){
      mockSettings.serializable();
    }
    if(annotation.stubOnly()){
      mockSettings.stubOnly();
    }
    if(annotation.lenient()){
      mockSettings.lenient();
    }

    // see @Mock answer default value
    mockSettings.defaultAnswer(annotation.answer());
    return Mockito.mock(type, mockSettings);
  }
}

代码示例来源:origin: org.mockito/mockito-core

private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) {
  MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ?
      withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces())
      : withSettings();
  return propagateSerializationSettings(mockSettings, parentMockSettings)
      .defaultAnswer(returnsDeepStubsAnswerUsing(returnTypeGenericMetadata));
}

代码示例来源:origin: org.infinispan/infinispan-core

protected void blockDataContainerIteration(final Cache<?, ?> cache, final CyclicBarrier barrier) {
   InternalDataContainer dataContainer = TestingUtil.extractComponent(cache, InternalDataContainer.class);
   final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(dataContainer);
   InternalDataContainer mockContainer = mock(InternalDataContainer.class, withSettings().defaultAnswer(forwardedAnswer));
   doAnswer(invocation -> {
     // Wait for main thread to sync up
     barrier.await(10, TimeUnit.SECONDS);
     // Now wait until main thread lets us through
     barrier.await(10, TimeUnit.SECONDS);

     return forwardedAnswer.answer(invocation);
   }).when(mockContainer).removeSegments(any());
   TestingUtil.replaceComponent(cache, InternalDataContainer.class, mockContainer, true);
  }
}

代码示例来源:origin: org.infinispan/infinispan-core

private void testFilterConverterUnusedDuringIteration(final StateListener<String, String> listener) {
 final List<CacheEntry<String, String>> initialValues = new ArrayList<CacheEntry<String, String>>(10);
 for (int i = 0; i < 10; i++) {
   String key = "key-" + i;
   String value = "value-" + i;
   initialValues.add(new ImmortalCacheEntry(key, value));
 }
 // Note we don't actually use the filter/converter to retrieve values since it is being mocked, thus we can assert
 // the filter/converter are not used by us
 CacheStream mockStream = mockStream();
 doReturn(initialValues.iterator()).when(mockStream).iterator();
 when(mockCache.withEncoding(any(Class.class), any(Class.class)).cacheEntrySet().stream()).thenReturn(mockStream);
 CacheEventFilter filter = mock(CacheEventFilter.class, withSettings().serializable());
 CacheEventConverter converter = mock(CacheEventConverter.class, withSettings().serializable());
 n.addListener(listener, filter, converter);
 verifyEvents(isClustered(listener), listener, initialValues);
 verify(filter, never()).accept(any(), any(), any(Metadata.class), any(), any(Metadata.class),
    any(EventType.class));
 verify(converter, never()).convert(any(), any(), any(Metadata.class), any(), any(Metadata.class),
    any(EventType.class));
}

代码示例来源:origin: mulesoft/mule

@Test
public void configFailsOnInitialize() throws Exception {
 final Lifecycle connProvider = mock(Lifecycle.class, withSettings().extraInterfaces(ConnectionProvider.class));
 final String expectedExceptionMessage = "Init failed!";
 doThrow(new RuntimeException(expectedExceptionMessage)).when(connProvider).initialise();
 when(connectionProviderResolver.resolve(any())).thenReturn(new Pair<>(connProvider, mock(ResolverSetResult.class)));
 expected.expectCause(hasMessage(is(InitialisationException.class.getName() + ": " + expectedExceptionMessage)));
 try {
  provider.get(event);
 } finally {
  verify(connProvider).initialise();
  verify(connProvider, never()).start();
  verify(connProvider, never()).stop();
  verify(connProvider).dispose();
 }
}

代码示例来源:origin: mulesoft/mule

public static MuleContextWithRegistry mockMuleContext() {
 final MuleContextWithRegistry muleContext =
   mock(DefaultMuleContext.class,
      withSettings().defaultAnswer(RETURNS_DEEP_STUBS).extraInterfaces(PrivilegedMuleContext.class).lenient());
 when(muleContext.getUniqueIdString()).thenReturn(UUID.getUUID());
 when(muleContext.getDefaultErrorHandler(empty())).thenReturn(new OnErrorPropagateHandler());
 StreamingManager streamingManager = mock(StreamingManager.class, RETURNS_DEEP_STUBS);
 try {
  MuleRegistry registry = mock(MuleRegistry.class, withSettings().lenient());
  when(muleContext.getRegistry()).thenReturn(registry);
  ComponentInitialStateManager componentInitialStateManager =
    mock(ComponentInitialStateManager.class, withSettings().lenient());
  when(componentInitialStateManager.mustStartMessageSource(any())).thenReturn(true);
  when(registry.lookupObject(ComponentInitialStateManager.SERVICE_ID)).thenReturn(componentInitialStateManager);
  doReturn(streamingManager).when(registry).lookupObject(StreamingManager.class);
  doReturn(mock(NotificationDispatcher.class)).when(registry).lookupObject(NotificationDispatcher.class);
  doReturn(mock(ObjectStoreManager.class, RETURNS_DEEP_STUBS)).when(registry).lookupObject(OBJECT_STORE_MANAGER);
 } catch (RegistrationException e) {
  throw new RuntimeException(e);
 }
 return muleContext;
}

代码示例来源:origin: pentaho/pentaho-kettle

private static JobEntryInterface createJobEntry( String directory ) {
 JobEntryInterface jobEntryInterface = mock( JobEntryInterface.class, withSettings().extraInterfaces( HasRepositoryDirectories.class ) );
 when( jobEntryInterface.isReferencedObjectEnabled() ).thenReturn( new boolean[] { true } );
 doAnswer( invocationOnMock -> new ObjectLocationSpecificationMethod[] { ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME } )
  .when( ( (HasRepositoryDirectories) jobEntryInterface ) ).getSpecificationMethods();
 doAnswer( invocationOnMock -> new String[] { directory } )
  .when( (HasRepositoryDirectories) jobEntryInterface ).getDirectories();
 return jobEntryInterface;
}

代码示例来源:origin: Alluxio/alluxio

@Before
public void before() throws Exception {
 mCommandManager = new CommandManager();
 // Create mock job info.
 mJobconfig = Mockito.mock(JobConfig.class, Mockito.withSettings().serializable());
 Mockito.when(mJobconfig.getName()).thenReturn("mock");
 mJobId = 1;
 // Create mock job definition.
 @SuppressWarnings("unchecked")
 JobDefinition<JobConfig, Serializable, Serializable> mockJobDefinition =
   Mockito.mock(JobDefinition.class);
 JobDefinitionRegistry singleton = PowerMockito.mock(JobDefinitionRegistry.class);
 Whitebox.setInternalState(JobDefinitionRegistry.class, "INSTANCE", singleton);
 Mockito.when(singleton.getJobDefinition(mJobconfig)).thenReturn(mockJobDefinition);
 mJobDefinition = mockJobDefinition;
 // Create test worker.
 mWorkerInfo = new WorkerInfo();
 mWorkerInfo.setId(0);
 mWorkerInfoList = Lists.newArrayList(mWorkerInfo);
 mUfsManager = Mockito.mock(UfsManager.class);
}

代码示例来源:origin: mulesoft/mule

@Test
public void testFailStartingMessageSourceOnLifecycleShouldStopStartedPipelineProcesses() throws Exception {
 // Need to start mule context to have endpoints started during flow start
 muleContext.start();
 MessageSource mockMessageSource = mock(MessageSource.class, withSettings().extraInterfaces(Startable.class, Stoppable.class));
 doThrow(new LifecycleException(mock(I18nMessage.class), mockMessageSource)).when(((Startable) mockMessageSource))
   .start();
 final List<Processor> processors = new ArrayList<>(flow.getProcessors());
 Processor mockMessageProcessor = spy(new LifecycleTrackerProcessor());
 processors.add(mockMessageProcessor);
 after();
 flow = (DefaultFlow) Flow.builder(FLOW_NAME, muleContext)
   .source(mockMessageSource)
   .processors(processors).build();
 flow.initialise();
 try {
  flow.start();
  fail();
 } catch (LifecycleException e) {
 }
 verify((Startable) mockMessageProcessor, times(1)).start();
 verify((Stoppable) mockMessageProcessor, times(1)).stop();
 verify((Startable) mockMessageSource, times(1)).start();
 verify((Stoppable) mockMessageSource, times(1)).stop();
}

代码示例来源:origin: dremio/dremio-oss

@Test
public void testOnMessageEOF() throws IOException {
 InputStream mis = mock(InputStream.class, withSettings().extraInterfaces(Seekable.class, PositionedReadable.class));
 doReturn(-1).when(mis).read(any(byte[].class), anyInt(), anyInt());
 FSDataInputStream fdis = new FSDataInputStream(mis);
 Response response = getResponse(7L, 4096, fdis);
 InOrder inOrder = Mockito.inOrder(mis);
 inOrder.verify((Seekable) mis).seek(7);
 inOrder.verify(mis).read(any(byte[].class), anyInt(), anyInt());
 assertEquals(-1, ((DFS.GetFileDataResponse) response.pBody).getRead());
 assertEquals(0, response.dBodies.length);
}

代码示例来源:origin: org.infinispan/infinispan-core

protected AsyncInterceptorChain mockEntrySet(final Cache<?, ?> cache, StreamMocking mocking) {
   AsyncInterceptorChain chain = TestingUtil.extractComponent(cache, AsyncInterceptorChain.class);
   AsyncInterceptorChain mockChain = spy(chain);
   doAnswer(i -> {
     CacheSet cacheSet = (CacheSet) i.callRealMethod();
     CacheSet mockSet = mock(CacheSet.class,
                 withSettings().defaultAnswer(delegatesTo(cacheSet)));

     when(mockSet.stream()).then(j -> {
      CacheStream stream = cacheSet.stream();
      return mockStream(stream, mocking);
     });

     return mockSet;
   }).when(mockChain).invoke(any(InvocationContext.class), any(EntrySetCommand.class));
   TestingUtil.replaceComponent(cache, AsyncInterceptorChain.class, mockChain, true);
   return chain;
  }
}

代码示例来源:origin: mulesoft/mule

@Test
 @Ignore("MULE-16210")
 public void originalExceptionThrownWhenStartAndStopOfSourceBothFail() throws Exception {
  final Exception startException = new IllegalArgumentException();
  final Exception stopException = new IllegalStateException();

  MessageSource source = mock(MessageSource.class, withSettings().extraInterfaces(Startable.class, Stoppable.class));
  doThrow(startException).when((Startable) source).start();
  doThrow(stopException).when((Stoppable) source).stop();

  muleContext = spy(muleContext);
  flow = (DefaultFlow) Flow.builder(FLOW_NAME, muleContext)
    .source(source)
    .processors(singletonList(mock(Processor.class)))
    .build();

  flow.initialise();
  muleContext.start();
  try {
   flow.start();
   fail("was expecting failure");
  } catch (LifecycleException e) {
   assertThat(e.getCause(), instanceOf(MuleException.class));
   assertThat(e.getCause().getCause(), sameInstance(startException));
  }

 }
}

代码示例来源:origin: apache/geode

@Before
public void before() {
 parseResult = mock(GfshParseResult.class);
 result = new ResultModel();
 executor = spy(CommandExecutor.class);
 testCommand = mock(SingleGfshCommand.class,
   withSettings().extraInterfaces(UpdateAllConfigurationGroupsMarker.class));
 ccService = spy(InternalConfigurationPersistenceService.class);
 configRegion = mock(AbstractRegion.class);
 doReturn(ccService).when(testCommand).getConfigurationPersistenceService();
 doCallRealMethod().when(ccService).updateCacheConfig(any(), any());
 doReturn(true).when(ccService).lockSharedConfiguration();
 doNothing().when(ccService).unlockSharedConfiguration();
 doReturn(configRegion).when(ccService).getConfigurationRegion();
}

代码示例来源:origin: org.infinispan/infinispan-core

protected void waitUntilNotificationRaised(final Cache<?, ?> cache, final CheckPoint checkPoint) {
 CacheNotifier cn = TestingUtil.extractComponent(cache, CacheNotifier.class);
 final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(cn);
 CacheNotifier mockNotifier = mock(CacheNotifier.class,
                  withSettings().extraInterfaces(ClusterCacheNotifier.class)
                         .defaultAnswer(forwardedAnswer));
 Answer answer = invocation -> {
   // Wait for main thread to sync up
   checkPoint.trigger("pre_raise_notification_invoked");
   // Now wait until main thread lets us through
   checkPoint.awaitStrict("pre_raise_notification_release", 10, TimeUnit.SECONDS);
   try {
    return forwardedAnswer.answer(invocation);
   } finally {
    // Wait for main thread to sync up
    checkPoint.trigger("post_raise_notification_invoked");
    // Now wait until main thread lets us through
    checkPoint.awaitStrict("post_raise_notification_release", 10, TimeUnit.SECONDS);
   }
 };
 doAnswer(answer).when(mockNotifier).notifyCacheEntryCreated(any(), any(), any(Metadata.class), eq(false),
    any(InvocationContext.class), any(FlagAffectedCommand.class));
 doAnswer(answer).when(mockNotifier).notifyCacheEntryModified(any(), any(), any(Metadata.class), any(),
    any(Metadata.class), anyBoolean(),
    any(InvocationContext.class), any(FlagAffectedCommand.class));
 doAnswer(answer).when(mockNotifier).notifyCacheEntryRemoved(any(), any(), any(Metadata.class), eq(false),
                               any(InvocationContext.class),
                               any(FlagAffectedCommand.class));
 TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true);
}

代码示例来源:origin: apache/samza

private TableWriteFunction createMockTableWriteFunction() {
 return mock(TableWriteFunction.class, withSettings().serializable());
}

代码示例来源:origin: google/j2objc

/**
 * Creates mock object of given class or interface.
 * <p>
 * See examples in javadoc for {@link Mockito} class
 * 
 * @param classToMock class or interface to mock
 * @return mock object
 */
public static <T> T mock(Class<T> classToMock) {
  return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

代码示例来源:origin: apache/samza

@Test
public void testStreamApplicationWithTableAndSideInput() {
 mockStreamAppDesc = new StreamApplicationDescriptorImpl(getRepartitionJoinStreamApplication(), mockConfig);
 // add table to the RepartitionJoinStreamApplication
 GenericInputDescriptor<KV<String, Object>> sideInput1 = inputSystemDescriptor.getInputDescriptor("sideInput1", defaultSerde);
 BaseTableDescriptor mockTableDescriptor = new MockLocalTableDescriptor("testTable", defaultSerde)
   .withSideInputs(Arrays.asList(sideInput1.getStreamId()))
   .withSideInputsProcessor(mock(SideInputsProcessor.class, withSettings().serializable()))
   .withConfig("mock.table.provider.config", "mock.config.value");
 // add side input and terminate at table in the appplication
 mockStreamAppDesc.getInputStream(sideInput1).sendTo(mockStreamAppDesc.getTable(mockTableDescriptor));
 StreamEdge sideInputEdge = new StreamEdge(new StreamSpec(sideInput1.getStreamId(), "sideInput1",
   inputSystemDescriptor.getSystemName()), false, false, mockConfig);
 // need to put the sideInput related stream configuration to the original config
 // TODO: this is confusing since part of the system and stream related configuration is generated outside the JobGraphConfigureGenerator
 // It would be nice if all system and stream related configuration is generated in one place and only intermediate stream
 // configuration is generated by JobGraphConfigureGenerator
 Map<String, String> configs = new HashMap<>(mockConfig);
 configs.putAll(sideInputEdge.generateConfig());
 mockConfig = spy(new MapConfig(configs));
 configureJobNode(mockStreamAppDesc);
 // create the JobGraphConfigureGenerator and generate the jobConfig for the jobNode
 JobNodeConfigurationGenerator configureGenerator = new JobNodeConfigurationGenerator();
 JobConfig jobConfig = configureGenerator.generateJobConfig(mockJobNode, "testJobGraphJson");
 Config expectedJobConfig = getExpectedJobConfig(mockConfig, mockJobNode.getInEdges());
 validateJobConfig(expectedJobConfig, jobConfig);
 Map<String, Serde> deserializedSerdes = validateAndGetDeserializedSerdes(jobConfig, 5);
 validateTableConfigure(jobConfig, deserializedSerdes, mockTableDescriptor);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void proxyingWorksIfInfoReturnsNullEntityManagerInterface() {
  EntityManagerFactory emf = mock(EntityManagerFactory.class,
      withSettings().extraInterfaces(EntityManagerFactoryInfo.class));
  // EntityManagerFactoryInfo.getEntityManagerInterface returns null
  assertThat(SharedEntityManagerCreator.createSharedEntityManager(emf), is(notNullValue()));
}

相关文章