org.mockito.Mockito.withSettings()方法的使用及代码示例

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

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

Mockito.withSettings介绍

[英]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 settings when the demand comes. Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.

See javadoc for MockSettings to learn about possible 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有两个原因。首先,为了方便在需要时添加其他模拟设置。第二,在不引入大量重载mock()方法的情况下,允许组合不同的mock设置。
请参阅javadoc了解MockSettings,以了解可能的mock设置。

代码示例

代码示例来源: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: org.mockito/mockito-core

/**
 * 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
 */
@CheckReturnValue
public static <T> T mock(Class<T> classToMock) {
  return mock(classToMock, withSettings());
}

代码示例来源: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: 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()));
}

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

/**
 * Creates mock with a specified strategy for its answers to interactions. 
 * It's quite advanced feature and typically you don't need it to write decent tests.
 * However it can be helpful when working with legacy systems.
 * <p>
 * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
 *
 * <pre class="code"><code class="java">
 *   Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
 *   Foo mockTwo = mock(Foo.class, new YourOwnAnswer()); 
 * </code></pre>
 * 
 * <p>See examples in javadoc for {@link Mockito} class</p>
 * 
 * @param classToMock class or interface to mock
 * @param defaultAnswer default answer for unstubbed methods
 *
 * @return mock object
 */
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
  return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}

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

/**
 * Creates class mock with a specified strategy for its answers to
 * interactions. It's quite advanced feature and typically you don't need it
 * to write decent tests. However it can be helpful when working with legacy
 * systems.
 * <p>
 * It is the default answer so it will be used <b>only when you don't</b>
 * stub the method call.
 *
 * <pre>
 * mockStatic(Foo.class, RETURNS_SMART_NULLS);
 * mockStatic(Foo.class, new YourOwnAnswer());
 * </pre>
 *
 * @param classMock
 *            class to mock
 * @param defaultAnswer
 *            default answer for unstubbed methods
 */
public static void mockStatic(Class<?> classMock, @SuppressWarnings("rawtypes") Answer defaultAnswer) {
  mockStatic(classMock, withSettings().defaultAnswer(defaultAnswer));
}

代码示例来源: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.powermock/powermock-api-mockito

/**
 * Creates mock with a specified strategy for its answers to interactions.
 * It's quite advanced feature and typically you don't need it to write
 * decent tests. However it can be helpful when working with legacy systems.
 * <p>
 * It is the default answer so it will be used <b>only when you don't</b>
 * stub the method call.
 *
 * <pre>
 * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
 * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
 * </pre>
 *
 * <p>
 * See examples in javadoc for {@link Mockito} class
 * </p>
 *
 * @param classToMock
 *            class or interface to mock
 * @param defaultAnswer
 *            default answer for unstubbed methods
 *
 * @return mock object
 */
public static <T> T mock(Class<T> classToMock, @SuppressWarnings("rawtypes") Answer defaultAnswer) {
  return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}

代码示例来源: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: org.mockito/mockito-core

/**
 * Creates mock with a specified strategy for its answers to interactions.
 * It's quite an advanced feature and typically you don't need it to write decent tests.
 * However it can be helpful when working with legacy systems.
 * <p>
 * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
 *
 * <pre class="code"><code class="java">
 *   Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
 *   Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
 * </code></pre>
 *
 * <p>See examples in javadoc for {@link Mockito} class</p>
 *
 * @param classToMock class or interface to mock
 * @param defaultAnswer default answer for unstubbed methods
 *
 * @return mock object
 */
@CheckReturnValue
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
  return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}

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

return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
    .spiedInstance(object)
    .defaultAnswer(CALLS_REAL_METHODS));

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

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

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

/**
 * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors. 
 * <p>
 * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. 
 * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
 * <p>
 * <b>If you use <code>&#064;Mock</code> annotation then you've got naming mocks for free!</b> <code>&#064;Mock</code> uses field name as mock name. {@link Mock Read more.}
 * <p>
 * 
 * See examples in javadoc for {@link Mockito} class
 * 
 * @param classToMock class or interface to mock
 * @param name of the mock 
 * @return mock object
 */
public static <T> T mock(Class<T> classToMock, String name) {
  return mock(classToMock, withSettings()
      .name(name)
      .defaultAnswer(RETURNS_DEFAULTS));
}

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

return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
    .spiedInstance(object)
    .defaultAnswer(CALLS_REAL_METHODS));

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

private BuilderInstruction buildInstruction22t(Opcode opcode, int offset) {
  BuilderInstruction instruction =
      mock(BuilderInstruction.class, withSettings().extraInterfaces(Instruction22t.class));
  when(location.getInstruction()).thenReturn(instruction);
  when(instruction.getLocation()).thenReturn(location);
  when(instruction.getCodeUnits()).thenReturn(0);
  when(instruction.getOpcode()).thenReturn(opcode);
  when(((Instruction22t) instruction).getRegisterA()).thenReturn(ARG1_REGISTER);
  when(((Instruction22t) instruction).getRegisterB()).thenReturn(ARG2_REGISTER);
  when(((Instruction22t) instruction).getCodeOffset()).thenReturn(offset);
  return instruction;
}

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

/**
 * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
 * <p>
 * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
 * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
 * <p>
 * <b>If you use <code>&#064;Mock</code> annotation then you've got naming mocks for free!</b> <code>&#064;Mock</code> uses field name as mock name. {@link Mock Read more.}
 * <p>
 *
 * See examples in javadoc for {@link Mockito} class
 *
 * @param classToMock class or interface to mock
 * @param name of the mock
 * @return mock object
 */
@CheckReturnValue
public static <T> T mock(Class<T> classToMock, String name) {
  return mock(classToMock, withSettings()
      .name(name)
      .defaultAnswer(RETURNS_DEFAULTS));
}

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

@CheckReturnValue
public static <T> T spy(Class<T> classToSpy) {
  return MOCKITO_CORE.mock(classToSpy, withSettings()
      .useConstructor()
      .defaultAnswer(CALLS_REAL_METHODS));

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

@Test
public void handlerMappingOrder() {
  HandlerMapping hm1 = mock(HandlerMapping.class, withSettings().extraInterfaces(Ordered.class));
  HandlerMapping hm2 = mock(HandlerMapping.class, withSettings().extraInterfaces(Ordered.class));
  when(((Ordered) hm1).getOrder()).thenReturn(1);
  when(((Ordered) hm2).getOrder()).thenReturn(2);
  when((hm1).getHandler(any())).thenReturn(Mono.just((Supplier<String>) () -> "1"));
  when((hm2).getHandler(any())).thenReturn(Mono.just((Supplier<String>) () -> "2"));
  StaticApplicationContext context = new StaticApplicationContext();
  context.registerBean("b2", HandlerMapping.class, () -> hm2);
  context.registerBean("b1", HandlerMapping.class, () -> hm1);
  context.registerBean(HandlerAdapter.class, SupplierHandlerAdapter::new);
  context.registerBean(HandlerResultHandler.class, StringHandlerResultHandler::new);
  context.refresh();
  DispatcherHandler dispatcherHandler = new DispatcherHandler(context);
  MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
  dispatcherHandler.handle(exchange).block(Duration.ofSeconds(0));
  assertEquals("1", exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(5)));
}

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

return mock(classToMock, withSettings().defaultAnswer(new AnswerReturnValuesAdapter(returnValues)));

相关文章

微信公众号

最新文章

更多