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

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

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

Mockito.stub介绍

[英]Stubs a method call with return value or an exception. E.g:

stub(mock.someMethod()).toReturn(10); 
//you can use flexible argument matchers, e.g: 
stub(mock.someMethod(anyString())).toReturn(10); 
//setting exception to be thrown: 
stub(mock.someMethod("some arg")).toThrow(new RuntimeException()); 
//you can stub with different behavior for consecutive method calls. 
//Last stubbing (e.g: toReturn("foo")) determines the behavior for further consecutive calls. 
stub(mock.someMethod("some arg")) 
.toThrow(new RuntimeException()) 
.toReturn("foo");

Some users find stub() confusing therefore Mockito#when(Object) is recommended over stub()

//Instead of: 
stub(mock.count()).toReturn(10); 
//You can do: 
when(mock.count()).thenReturn(10);

For stubbing void methods with throwables see: Mockito#doThrow(Throwable)

Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing.

Once stubbed, the method will always return stubbed value regardless of how many times it is called.

Last stubbing is more important - when you stubbed the same method with the same arguments many times.

Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.
[中]

代码示例

代码示例来源:origin: aol/micro-server

@Before
public void setup() {
  memcachedClient = mock(MemcachedClient.class);
  stub(memcachedClient.get("key1")).toReturn("value1");
  stub(memcachedClient.get("key2")).toReturn("value2");
  OperationFuture<Boolean> mockedFuture = mock(OperationFuture.class);
  stub(memcachedClient.add("keyAdd", 3600, "valueadd")).toReturn(mockedFuture);
}

代码示例来源:origin: pholser/junit-quickcheck

@Test public void shrinkingChoosesAComponentCapableOfShrinkingTheValue() {
    stub(first.canShrink(7)).toReturn(true);
    stub(second.canShrink(7)).toReturn(false);
    stub(third.canShrink(7)).toReturn(true);
    when(first.types()).thenReturn(singletonList(Integer.class));
    when(first.doShrink(random, 7)).thenReturn(asList(3, 6));
    when(random.nextInt(9)).thenReturn(1);

    assertEquals(asList(3, 6), composite.shrink(random, 7));
    verify(first, atLeastOnce()).doShrink(random, 7);
  }
}

代码示例来源:origin: openmrs/openmrs-core

@Test(expected = org.openmrs.api.ProgramNameDuplicatedException.class)
public void getProgramByName_shouldFailWhenTwoProgramsFoundWithSameName() {
  ProgramWorkflowDAO mockDao = Mockito.mock(ProgramWorkflowDAO.class);
  List<Program> programsWithGivenName = new ArrayList<>();
  Program program1 = new Program("A name");
  Program program2 = new Program("A name");
  programsWithGivenName.add(program1);
  programsWithGivenName.add(program2);
  Mockito.stub(mockDao.getProgramsByName("A name", false)).toReturn(programsWithGivenName);
  Mockito.stub(mockDao.getProgramsByName("A name", true)).toReturn(programsWithGivenName);
  pws.setProgramWorkflowDAO(mockDao);
  pws.getProgramByName("A name");
}

代码示例来源:origin: openmrs/openmrs-core

@Test
public void getProgramByName_shouldReturnNullWhenThereIsNoProgramForGivenName() {
  ProgramWorkflowDAO mockDao = Mockito.mock(ProgramWorkflowDAO.class);
  List<Program> noProgramWithGivenName = new ArrayList<>();
  Mockito.stub(mockDao.getProgramsByName("A name", false)).toReturn(noProgramWithGivenName);
  Mockito.stub(mockDao.getProgramsByName("A name", true)).toReturn(noProgramWithGivenName);
  pws.setProgramWorkflowDAO(mockDao);
  Assert.assertNull(pws.getProgramByName("A name"));
}

代码示例来源:origin: org.teiid/teiid-spring-boot-starter

@Before
public void setup() {
  this.server = Mockito.mock(TeiidServer.class);
  this.context = Mockito.mock(ApplicationContext.class);
  Environment env = Mockito.mock(Environment.class);
  Mockito.stub(env.getProperty(Mockito.anyString())).toReturn(null);
  Mockito.stub(context.getEnvironment()).toReturn(env);
}

代码示例来源:origin: teiid/teiid

static StatementImpl createMockStatement(int cursorType, MockSettings mockSetting) throws SQLException {
  StatementImpl statement = mock(StatementImpl.class, mockSetting);
  DQP dqp = mock(DQP.class);
  stub(statement.getDQP()).toReturn(dqp);
  stub(statement.getResultSetType()).toReturn(cursorType);
  TimeZone tz = TimeZone.getTimeZone("GMT-06:00"); //$NON-NLS-1$
  TimeZone serverTz = TimeZone.getTimeZone("GMT-05:00"); //$NON-NLS-1$
  stub(statement.getDefaultCalendar()).toReturn(Calendar.getInstance(tz));
  stub(statement.getServerTimeZone()).toReturn(serverTz);
  return statement;
}

代码示例来源:origin: it.tidalwave.metadata/it-tidalwave-metadata

public Metadata findOrCreateMetadata (final DataObject dataObject)
  {
   final Metadata metadata = Mockito.mock(Metadata.class);
   Mockito.stub(metadata.getDataObject()).toReturn(dataObject);
   creationCount++;
   return metadata;
  }
}

代码示例来源:origin: teiid/teiid

@Before public void setUp() throws Exception {
  server = new TransactionServerImpl();
  tm = Mockito.mock(TransactionManager.class);
  txn = Mockito.mock(javax.transaction.Transaction.class);
  Mockito.stub(tm.getTransaction()).toReturn(txn);
  Mockito.stub(tm.suspend()).toReturn(txn);
  xaImporter = Mockito.mock(XAImporter.class);
  Mockito.stub(xaImporter.importTransaction(Mockito.any(), Mockito.any(), Mockito.eq(TIMEOUT))).toReturn(txn);
  server.setXaImporter(xaImporter);
  server.setTransactionManager(tm);
}

代码示例来源:origin: novoda/simple-easy-xml-parser

@Before
public void setUp() {
  initMocks(this);
  stub(mockFactory.getListElementFinder(Mockito.<BodyMarshaller<Object>>any(), Mockito.<ParseWatcher<Object>>any())).toReturn(mockListCreator);
  listParser = new ListParser<Object>("individualItemTag", mockFactory, mockMarshaller);
}

代码示例来源:origin: novoda/sqlite-provider

@Before
public void init() {
  MockitoAnnotations.initMocks(this);
  stub(builder.query((SQLiteDatabase) anyObject(), (String[]) anyObject(), anyString(), (String[]) anyObject(), anyString(),
      anyString(), anyString(), anyString())).toReturn(mockCursor);
  stub(db.rawQuery(anyString(), (String[]) anyObject())).toReturn(mockCursor);
  provider = new SQLiteProviderImpl();
  provider.onCreate();
}

代码示例来源:origin: teiid/teiid

@Test public void testPropertiesOverride() throws Exception {
  ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
  Properties p = new Properties();
  p.setProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.TRUE.toString());
  Mockito.stub(conn.getExecutionProperties()).toReturn(p);
  StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  assertEquals(Boolean.TRUE.toString(), statement.getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
  statement.setExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.FALSE.toString());
  assertEquals(Boolean.FALSE.toString(), statement.getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
  assertEquals(Boolean.TRUE.toString(), p.getProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
}

代码示例来源:origin: teiid/teiid

@Test public void testUseJDBC4ColumnNameAndLabelSemantics() throws Exception {
  ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
  Properties p = new Properties();
  p.setProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS, "false");
  Mockito.stub(conn.getExecutionProperties()).toReturn(p);
  StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  assertEquals(Boolean.FALSE.toString(), statement.getExecutionProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
  
}

代码示例来源:origin: teiid/teiid

@Test public void testTimeoutProperty() throws Exception {
  ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
  Properties p = new Properties();
  p.setProperty(ExecutionProperties.QUERYTIMEOUT, "2");
  Mockito.stub(conn.getExecutionProperties()).toReturn(p);
  StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  assertEquals(2, statement.getQueryTimeout());
}

代码示例来源:origin: teiid/teiid

@Test
  public void testReferenceTableName() {
    Table table = Mockito.mock(Table.class);
    Mockito.stub(table.getName()).toReturn("table"); //$NON-NLS-1$
    
    KeyRecord pk = Mockito.mock(KeyRecord.class);
    Mockito.stub(pk.getParent()).toReturn(table);
    
    ForeignKey fk = new ForeignKey();
    fk.setPrimaryKey(pk);
    
    assertEquals("table", fk.getReferenceTableName()); //$NON-NLS-1$
  }
}

代码示例来源:origin: teiid/teiid

@Test public void testNullCategory() {
  FunctionMethod method = new FunctionMethod(
      "dummy", null, null, PushDown.MUST_PUSHDOWN, "nonexistentClass", "noMethod",  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
      new ArrayList<FunctionParameter>(0), 
       new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), //$NON-NLS-1$
       false, Determinism.DETERMINISTIC);
  
  Collection<org.teiid.metadata.FunctionMethod> list = Arrays.asList(method);
  FunctionMetadataSource fms = Mockito.mock(FunctionMetadataSource.class);
  Mockito.stub(fms.getFunctionMethods()).toReturn(list);
  FunctionTree ft = new FunctionTree("foo", fms);
  assertEquals(1, ft.getFunctionsInCategory(FunctionCategoryConstants.MISCELLANEOUS).size());
}

代码示例来源:origin: teiid/teiid

@Test public void testSetPayloadStatement() throws Exception {
  ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
  Properties p = new Properties();
  Mockito.stub(conn.getExecutionProperties()).toReturn(p);
  StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  assertFalse(statement.execute("set payload foo bar")); //$NON-NLS-1$
}

代码示例来源:origin: teiid/teiid

@Test public void testSetAuthorizationStatement() throws Exception {
  ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
  Properties p = new Properties();
  Mockito.stub(conn.getExecutionProperties()).toReturn(p);
  StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  assertFalse(statement.execute("set session authorization bar")); //$NON-NLS-1$
  Mockito.verify(conn).changeUser("bar", null);
}

代码示例来源:origin: teiid/teiid

@Test public void testClearPolicies() {
  DQPWorkContext message = new DQPWorkContext();
  message.setSession(Mockito.mock(SessionMetadata.class));
  Mockito.stub(message.getSession().getVdb()).toReturn(new VDBMetaData());
  Map<String, DataPolicy> map = message.getAllowedDataPolicies();
  map.put("role", Mockito.mock(DataPolicy.class)); //$NON-NLS-1$
  assertFalse(map.isEmpty());
  
  message.setSession(Mockito.mock(SessionMetadata.class));
  Mockito.stub(message.getSession().getVdb()).toReturn(new VDBMetaData());
  map = message.getAllowedDataPolicies();
  assertTrue(map.isEmpty());
}

代码示例来源:origin: teiid/teiid

@Test public void testLogonFailsWithMultipleHosts() throws Exception {
  Properties p = new Properties();
  SocketServerInstanceFactory instanceFactory = Mockito.mock(SocketServerInstanceFactory.class);
  Mockito.stub(instanceFactory.getServerInstance((HostInfo)Mockito.anyObject())).toThrow(new SingleInstanceCommunicationException());
  UrlServerDiscovery discovery = new UrlServerDiscovery(new TeiidURL("mm://host1:1,host2:2")); //$NON-NLS-1$
  try {
    new SocketServerConnection(instanceFactory, false, discovery, p);
    fail("exception expected"); //$NON-NLS-1$
  } catch (CommunicationException e) {
    assertEquals("TEIID20021 No valid host available. Attempted connections to: [host1:1, host2:2]", e.getMessage()); //$NON-NLS-1$
  }
}

代码示例来源:origin: teiid/teiid

@Test(expected=TeiidSQLException.class) public void testResultsMessageException() throws Exception {
  ResultsMessage resultsMsg = exampleMessage(exampleResults1(1), new String[] { "IntNum" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$
  resultsMsg.setFinalRow(-1);
  ResultsMessage next = new ResultsMessage();
  next.setException(new Throwable());
  ResultsFuture<ResultsMessage> rf = new ResultsFuture<ResultsMessage>();
  rf.getResultsReceiver().receiveResults(next);
  Mockito.stub(statement.getDQP().processCursorRequest(0, 2, 0)).toReturn(rf);
  ResultSetImpl cs = new ResultSetImpl(resultsMsg, statement, null, 2);
  cs.next();
  cs.next();
}

相关文章

微信公众号

最新文章

更多