org.mockito.MockSettings.serializable()方法的使用及代码示例

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

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

MockSettings.serializable介绍

[英]Configures the mock to be serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.

WARNING: This should be rarely used in unit testing.

The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This was in a web environment and the objects from the external dependency were being serialized to pass between layers.

Example:

List serializableMock = mock(List.class, withSettings().serializable());

[中]将模拟配置为可序列化。有了这个特性,您可以在需要依赖项可序列化的地方使用模拟。
警告:这在单元测试中应该很少使用。
该行为是针对具有不可靠外部依赖关系的BDD规范的特定用例实现的。这是在一个web环境中,外部依赖项中的对象被序列化以在层之间传递。
例子:

List serializableMock = mock(List.class, withSettings().serializable());

代码示例

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

private MockSettings propagateSerializationSettings(MockSettings mockSettings, MockCreationSettings parentMockSettings) {
  return mockSettings.serializable(parentMockSettings.getSerializableMode());
}

代码示例来源: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: 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: spring-projects/spring-framework

@Test
public void testPrivatePersistenceContextField() throws Exception {
  mockEmf = mock(EntityManagerFactory.class, withSettings().serializable());
  GenericApplicationContext gac = new GenericApplicationContext();
  gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
  gac.registerBeanDefinition("annotationProcessor",
      new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
  gac.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
      new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
  gac.registerBeanDefinition(FactoryBeanWithPersistenceContextField.class.getName(),
      new RootBeanDefinition(FactoryBeanWithPersistenceContextField.class));
  gac.refresh();
  DefaultPrivatePersistenceContextField bean = (DefaultPrivatePersistenceContextField) gac.getBean(
      DefaultPrivatePersistenceContextField.class.getName());
  FactoryBeanWithPersistenceContextField bean2 = (FactoryBeanWithPersistenceContextField) gac.getBean(
      "&" + FactoryBeanWithPersistenceContextField.class.getName());
  assertNotNull(bean.em);
  assertNotNull(bean2.em);
  assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));
  assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean2.em));
}

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

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testPublicExtendedPersistenceContextSetterWithEntityManagerInfoAndSerialization() throws Exception {
  EntityManager mockEm = mock(EntityManager.class, withSettings().serializable());
  given(mockEm.isOpen()).willReturn(true);
  EntityManagerFactoryWithInfo mockEmf = mock(EntityManagerFactoryWithInfo.class);
  given(mockEmf.getNativeEntityManagerFactory()).willReturn(mockEmf);
  given(mockEmf.getJpaDialect()).willReturn(new DefaultJpaDialect());
  given(mockEmf.getEntityManagerInterface()).willReturn((Class)EntityManager.class);
  given(mockEmf.getBeanClassLoader()).willReturn(getClass().getClassLoader());
  given(mockEmf.createEntityManager()).willReturn(mockEm);
  GenericApplicationContext gac = new GenericApplicationContext();
  gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
  gac.registerBeanDefinition("annotationProcessor",
      new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
  gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
      new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
  gac.refresh();
  DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
      DefaultPublicPersistenceContextSetter.class.getName());
  assertNotNull(bean.em);
  assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));
}

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

private TableReadFunction createMockTableReadFunction() {
 return mock(TableReadFunction.class, withSettings().serializable());
}

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

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

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

private RateLimiter createMockRateLimiter() {
 return mock(RateLimiter.class, withSettings().serializable());
}

代码示例来源:origin: org.springframework.boot/spring-boot-test

@SuppressWarnings("unchecked")
public <T> T createMock(String name) {
  MockSettings settings = MockReset.withSettings(getReset());
  if (StringUtils.hasLength(name)) {
    settings.name(name);
  }
  if (!this.extraInterfaces.isEmpty()) {
    settings.extraInterfaces(ClassUtils.toClassArray(this.extraInterfaces));
  }
  settings.defaultAnswer(this.answer);
  if (this.serializable) {
    settings.serializable();
  }
  return (T) Mockito.mock(this.typeToMock.resolve(), settings);
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-core

@SuppressWarnings("unchecked")
@Before
public void setUp() {
 mockCombineFn = mock(CombineFnWithContext.class, withSettings().serializable());
}

代码示例来源:origin: org.apache.beam/beam-sdks-java-io-google-cloud-platform

public FakeServiceFactory() {
 synchronized (lock) {
  index = count++;
  mockSpanners.add(mock(Spanner.class, withSettings().serializable()));
  mockDatabaseClients.add(mock(DatabaseClient.class, withSettings().serializable()));
  mockBatchClients.add(mock(BatchClient.class, withSettings().serializable()));
 }
 when(mockSpanner().getDatabaseClient(Matchers.any(DatabaseId.class)))
   .thenReturn(mockDatabaseClient());
 when(mockSpanner().getBatchClient(Matchers.any(DatabaseId.class)))
   .thenReturn(mockBatchClient());
}

代码示例来源:origin: name.falgout.jeffrey.testing.junit5/mockito-extension

@Override
 public Object getParameterValue(Parameter parameter) {
  Mock annotation = parameter.getAnnotation(Mock.class);
  MockSettings settings = Mockito.withSettings();
  if (annotation.extraInterfaces().length > 0) {
   settings.extraInterfaces(annotation.extraInterfaces());
  }
  if (annotation.serializable()) {
   settings.serializable();
  }
  settings.name(annotation.name().isEmpty() ? parameter.getName() : annotation.name());
  settings.defaultAnswer(annotation.answer());

  return Mockito.mock(parameter.getType(), settings);
 }
}

代码示例来源: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: org.apache.beam/beam-runners-core-java

@Before
public void setUp() {
 MockitoAnnotations.initMocks(this);
 mockTriggerStateMachine = mock(TriggerStateMachine.class, withSettings().serializable());
 @SuppressWarnings("unchecked")
 PCollectionView<Integer> mockViewUnchecked =
   mock(PCollectionView.class, withSettings().serializable());
 mockView = mockViewUnchecked;
 firstWindow = new IntervalWindow(new Instant(0), new Instant(10));
}

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

public void testMetadataAvailable() {
 final List<CacheEntry<String, String>> initialValues = new ArrayList<>(10);
 for (int i = 0; i < 10; i++) {
   String key = "key-" + i;
   String value = "value-" + i;
   initialValues.add(new TransientMortalCacheEntry(key, value, i, -1, System.currentTimeMillis()));
 }
 // 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());
 StateListener<String, String> listener = new StateListenerClustered();
 n.addListener(listener, filter, converter);
 verifyEvents(isClustered(listener), listener, initialValues);
 for (CacheEntryEvent<String, String> event : listener.events) {
   String key = event.getKey();
   Metadata metadata = event.getMetadata();
   assertNotNull(metadata);
   assertEquals(metadata.lifespan(), -1);
   assertEquals(metadata.maxIdle(), Long.parseLong(key.substring(4)));
 }
}

代码示例来源: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: apache/samza

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");
StreamEdge sideInputEdge = new StreamEdge(new StreamSpec(sideInput1.getStreamId(), "sideInput1",

相关文章