当前位置: 首页>>代码示例>>Java>>正文


Java Mockito类代码示例

本文整理汇总了Java中org.mockito.Mockito的典型用法代码示例。如果您正苦于以下问题:Java Mockito类的具体用法?Java Mockito怎么用?Java Mockito使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Mockito类属于org.mockito包,在下文中一共展示了Mockito类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: validMinimumGasPrice

import org.mockito.Mockito; //导入依赖的package包/类
@Test
public void validMinimumGasPrice() {
    Transaction tx1 = Mockito.mock(Transaction.class);
    Transaction tx2 = Mockito.mock(Transaction.class);
    Transaction tx3 = Mockito.mock(Transaction.class);

    Mockito.when(tx1.getGasPriceAsInteger()).thenReturn(BigInteger.valueOf(10));
    Mockito.when(tx2.getGasPriceAsInteger()).thenReturn(BigInteger.valueOf(11));
    Mockito.when(tx3.getGasPriceAsInteger()).thenReturn(BigInteger.valueOf(500000000));

    TxValidatorMinimuGasPriceValidator tvmgpv = new TxValidatorMinimuGasPriceValidator();


    Assert.assertTrue(tvmgpv.validate(tx1, null, null, BigInteger.valueOf(10), Long.MAX_VALUE, false));
    Assert.assertTrue(tvmgpv.validate(tx2, null, null, BigInteger.valueOf(10), Long.MAX_VALUE, false));
    Assert.assertTrue(tvmgpv.validate(tx3, null, null, BigInteger.valueOf(10), Long.MAX_VALUE, false));
}
 
开发者ID:rsksmart,项目名称:rskj,代码行数:18,代码来源:TxValidatorMinimumGasPriceValidatorTest.java

示例2: testValidateResponseJsonErrorKnownException

import org.mockito.Mockito; //导入依赖的package包/类
@Test
public void testValidateResponseJsonErrorKnownException() throws IOException {
  Map<String, Object> json = new HashMap<String, Object>();
  json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, IllegalStateException.class.getSimpleName());
  json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, IllegalStateException.class.getName());
  json.put(HttpExceptionUtils.ERROR_MESSAGE_JSON, "EX");
  Map<String, Object> response = new HashMap<String, Object>();
  response.put(HttpExceptionUtils.ERROR_JSON, json);
  ObjectMapper jsonMapper = new ObjectMapper();
  String msg = jsonMapper.writeValueAsString(response);
  InputStream is = new ByteArrayInputStream(msg.getBytes());
  HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
  Mockito.when(conn.getErrorStream()).thenReturn(is);
  Mockito.when(conn.getResponseMessage()).thenReturn("msg");
  Mockito.when(conn.getResponseCode()).thenReturn(
      HttpURLConnection.HTTP_BAD_REQUEST);
  try {
    HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED);
    Assert.fail();
  } catch (IllegalStateException ex) {
    Assert.assertEquals("EX", ex.getMessage());
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:24,代码来源:TestHttpExceptionUtils.java

示例3: setUp

import org.mockito.Mockito; //导入依赖的package包/类
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  gifHeader = Mockito.spy(new GifHeader());
  when(parser.parseHeader()).thenReturn(gifHeader);
  when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);

  when(decoderFactory.build(isA(GifDecoder.BitmapProvider.class),
      eq(gifHeader), isA(ByteBuffer.class), anyInt()))
      .thenReturn(gifDecoder);

  List<ImageHeaderParser> parsers = new ArrayList<ImageHeaderParser>();
  parsers.add(new DefaultImageHeaderParser());

  options = new Options();
  decoder =
      new ByteBufferGifDecoder(
          RuntimeEnvironment.application,
          parsers,
          bitmapPool,
          new LruArrayPool(ARRAY_POOL_SIZE_BYTES),
          parserPool,
          decoderFactory);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:26,代码来源:ByteBufferGifDecoderTest.java

示例4: testExecute_WhenDomainIsNotFound_ThrowsException

import org.mockito.Mockito; //导入依赖的package包/类
@Test
public void testExecute_WhenDomainIsNotFound_ThrowsException() throws Exception {
    // Arrange.
    SecurityGroup sg = registerSecurityGroup(1L, "projectId", "projectName", 1L, "sgName");
    sg.addSecurityGroupMember(newSGMWithPort(1L));

    ostRegisterPorts(sg);

    // domain id null
    registerDomain(null, sg);

    this.exception.expect(Exception.class);
    this.exception
    .expectMessage(String.format("A domain was not found for the project: '%s' and Security Group: '%s",
            sg.getProjectName(), sg.getName()));

    CreatePortGroupTask task = this.factoryTask.create(sg);

    // Act.
    task.execute();

    // Assert.
    verify(this.em, Mockito.never()).merge(any());
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:25,代码来源:CreatePortGroupTaskTest.java

示例5: testExecute_WhenPortGroupIsNotFound_ThrowsException

import org.mockito.Mockito; //导入依赖的package包/类
@Test
public void testExecute_WhenPortGroupIsNotFound_ThrowsException() throws Exception {
    // Arrange.
    SecurityGroup sg = registerSecurityGroup(1L, "projectId", "projectName", 1L, "sgName");
    sg.addSecurityGroupMember(newSGMWithPort(1L));

    ostRegisterPorts(sg);

    registerDomain(UUID.randomUUID().toString(), sg);

    // network element/portGroup null
    NetworkElement ne = null;
    SdnRedirectionApi redirectionApi = registerNetworkElement(ne);
    registerNetworkRedirectionApi(redirectionApi, sg.getVirtualizationConnector());

    this.exception.expect(Exception.class);
    this.exception.expectMessage(String.format("RegisterNetworkElement failed to return PortGroup"));

    CreatePortGroupTask task = this.factoryTask.create(sg);
    // Act.
    task.execute();

    // Assert.
    verify(this.em, Mockito.never()).merge(any());
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:26,代码来源:CreatePortGroupTaskTest.java

示例6: createMockFacesContext

import org.mockito.Mockito; //导入依赖的package包/类
private static FacesContext createMockFacesContext () throws MalformedURLException {
    FacesContext ctx = Mockito.mock(FacesContext.class);
    CompositeELResolver cer = new CompositeELResolver();
    FacesELContext elc = new FacesELContext(cer, ctx);
    ServletRequest requestMock = Mockito.mock(ServletRequest.class);
    ServletContext contextMock = Mockito.mock(ServletContext.class);
    URL url = new URL("file:///");
    Mockito.when(contextMock.getResource(Matchers.anyString())).thenReturn(url);
    Mockito.when(requestMock.getServletContext()).thenReturn(contextMock);
    Answer<?> attrContext = new MockRequestContext();
    Mockito.when(requestMock.getAttribute(Matchers.anyString())).thenAnswer(attrContext);
    Mockito.doAnswer(attrContext).when(requestMock).setAttribute(Matchers.anyString(), Matchers.any());
    cer.add(new MockELResolver(requestMock));
    cer.add(new BeanELResolver());
    cer.add(new MapELResolver());
    Mockito.when(ctx.getELContext()).thenReturn(elc);
    return ctx;
}
 
开发者ID:pimps,项目名称:ysoserial-modified,代码行数:19,代码来源:MyfacesTest.java

示例7: testCreate

import org.mockito.Mockito; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void testCreate() {
    DiscoveryService discoveryService = Mockito.mock(DiscoveryService.class);
    StreamId<Object> sourceStreamId = Mockito.mock(StreamId.class);

    Publisher<Object> sourceReactiveStream = Mockito.mock(Publisher.class);
    Publisher<Object> newReactiveStream = Mockito.mock(Publisher.class);
    Mockito.when(discoveryService.discover(sourceStreamId)).thenReturn(sourceReactiveStream);

    Function<List<Publisher<Object>>, Publisher<Object>> transformationFunction = Mockito.mock(Function.class);
    Mockito.when(transformationFunction.apply(Collections.singletonList(sourceReactiveStream)))
            .thenReturn(newReactiveStream);

    CompositionStreamId<Object, Object> compositionStreamId = new CompositionStreamId<>(sourceStreamId,
            transformationFunction);
    ErrorStreamPair<Object> optionalCompositionReactiveStream = compositionStreamFactory
            .create(compositionStreamId, discoveryService);

    assertThat(optionalCompositionReactiveStream.data()).isEqualTo(newReactiveStream);
    Mockito.verify(transformationFunction).apply(Collections.singletonList(sourceReactiveStream));
}
 
开发者ID:streamingpool,项目名称:streamingpool-core,代码行数:23,代码来源:CompositionStreamFactoryTest.java

示例8: setUp

import org.mockito.Mockito; //导入依赖的package包/类
@Before
    public void setUp() throws Exception, LiRestResponseException {

        mContext = Mockito.mock(Activity.class);
        mMockSharedPreferences = Mockito.mock(SharedPreferences.class);
        resource = Mockito.mock(Resources.class);
        when(resource.getBoolean(anyInt())).thenReturn(true);
        when(mContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mMockSharedPreferences);
        when(mMockSharedPreferences.getString(anyString(), anyString())).thenReturn("foobar");
        when(mContext.getResources()).thenReturn(resource);
        liSDKManager = LiSDKManager.init(mContext, TestHelper.getTestAppCredentials());
        liRestv2Client = mock(LiRestv2Client.class);
        MockitoAnnotations.initMocks(this);
//        when(liSDKManager.getTenant()).thenReturn("test");
        liClientManager = mock(LiClientManager.class);
        PowerMockito.mockStatic(LiRestv2Client.class);
        BDDMockito.given(LiRestv2Client.getInstance()).willReturn(liRestv2Client);
        PowerMockito.mockStatic(LiClientManager.class);
    }
 
开发者ID:lithiumtech,项目名称:li-android-sdk-core,代码行数:20,代码来源:LiBaseClientTest.java

示例9: getCategory_should_return_valid_response

import org.mockito.Mockito; //导入依赖的package包/类
@Test(groups = "SearchCategory.getCategory")
public void getCategory_should_return_valid_response() {
    try {
        PowerMockito
                .when(HttpUtils.doGet(Mockito.anyString(),
                        Matchers.<Map<String, String>> any()))
                .thenReturn(TEST_CATEGORY_RESPONSE);
        SearchCategory api = new SearchCategory(config);
        SearchCategoryRequest request = new SearchCategoryRequest()
                .setCategoryId(1043).setLocale("en-US");
        StockFileCategory category = api.getCategory(request);
        Assert.assertEquals(category.getName(), "Travel");
        Assert.assertEquals(category.getId().intValue(), 1043);
        Assert.assertEquals(category.getLink(), "/Category/travel/1043");
    } catch (Exception e) {
        Assert.fail("Didn't expect the exception here!", e);
    }
}
 
开发者ID:adobe,项目名称:stock-api-sdk,代码行数:19,代码来源:SearchCategoryTest.java

示例10: testBinaryOperator

import org.mockito.Mockito; //导入依赖的package包/类
/**
 * V1 BOp V2 -> BOp V1 V2
 */
@SuppressWarnings("unchecked")
@Test
public void testBinaryOperator() {
	BinaryOperatorRepresentation<Integer> binaryOperator = Mockito.mock(BinaryOperatorRepresentation.class);
	Mockito.when(binaryOperator.isOperator()).thenReturn(true);
	ValueOperatorRepresentation<Integer> value1 = Mockito.mock(ValueOperatorRepresentation.class);
	ValueOperatorRepresentation<Integer> value2 = Mockito.mock(ValueOperatorRepresentation.class);
	INPUT.add(value1);
	INPUT.add(binaryOperator);
	INPUT.add(value2);
	ArrayList<IElementRepresentation<Integer>> RESULT = convertor.convert(INPUT);
	assertEquals(binaryOperator, RESULT.get(0));
	assertEquals(value1, RESULT.get(1));
	assertEquals(value2, RESULT.get(2));
}
 
开发者ID:MickaelAlvarez,项目名称:InfixToObject,代码行数:19,代码来源:InfixToPrefixTest.java

示例11: init_Verifies_Permissions_NoPopupWhenGranted

import org.mockito.Mockito; //导入依赖的package包/类
@Test
public void init_Verifies_Permissions_NoPopupWhenGranted() throws Exception {
    ReactNativeCallEventsModule instance = getInstance();

    PowerMockito.mockStatic(ContextCompat.class);
    PowerMockito.when(ContextCompat.checkSelfPermission(mockActivity, Manifest.permission.READ_PHONE_STATE))
            .thenReturn(PackageManager.PERMISSION_GRANTED);

    PowerMockito.mockStatic(ActivityCompat.class);
    PowerMockito.doNothing().when(ActivityCompat.class);
    ActivityCompat.requestPermissions(mockActivity, new String[]{Manifest.permission.READ_PHONE_STATE}, 1);

    instance.init(false, false);

    PowerMockito.verifyStatic();
    ContextCompat.checkSelfPermission(mockActivity, Manifest.permission.READ_PHONE_STATE);

    PowerMockito.verifyStatic(Mockito.never());
    ActivityCompat.requestPermissions(Mockito.any(Activity.class), Mockito.any(String[].class), Mockito.anyInt());
}
 
开发者ID:HS2-SOLUTIONS,项目名称:react-native-call-events,代码行数:21,代码来源:ReactNativeCallEventsModuleTest.java

示例12: setup

import org.mockito.Mockito; //导入依赖的package包/类
@Before
public void setup() throws IOException, InterruptedException {

  // Prepare site.
  when(envVarsMock.get("JIRA_SITE")).thenReturn("LOCAL");
  when(envVarsMock.get("BUILD_URL")).thenReturn("http://localhost:8080/jira-testing/job/01");

  PowerMockito.mockStatic(Site.class);
  Mockito.when(Site.get(any())).thenReturn(siteMock);
  when(siteMock.getService()).thenReturn(jiraServiceMock);

  when(runMock.getCauses()).thenReturn(null);
  when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
  doNothing().when(printStreamMock).println();

  final ResponseDataBuilder<Object> builder = ResponseData.builder();
  when(jiraServiceMock.updateIssue(anyString(), any()))
      .thenReturn(builder.successful(true).code(200).message("Success").build());

  when(contextMock.get(Run.class)).thenReturn(runMock);
  when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
  when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
}
 
开发者ID:jenkinsci,项目名称:jira-steps-plugin,代码行数:24,代码来源:EditIssueStepTest.java

示例13: prepareRollback

import org.mockito.Mockito; //导入依赖的package包/类
@Ignore
public void prepareRollback() throws Exception {
    // given
    ServiceInstance si = Mockito.spy(new ServiceInstance());
    si.setSubscriptionId("subscriptionId");
    si.setReferenceId("refId");
    String expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\"><properties><entry key=\"ROLLBACK_SUBSCRIPTIONREF\">refId</entry><entry key=\"KEY2\">VALUE2</entry><entry key=\"ROLLBACK_SUBSCRIPTIONID\">subscriptionId</entry><entry key=\"KEY1\">VALUE1</entry></properties>";

    HashMap<String, String> params = new HashMap<>();
    params.put("KEY1", "VALUE1");
    params.put("KEY2", "VALUE2");

    Mockito.doReturn(params).when(si).getParameterMap();

    // when
    si.prepareRollback();

    // then
    assertEquals(expectedXML, removeFormatting(si.getRollbackParameters()));
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:21,代码来源:ServiceInstanceTest.java

示例14: waitForBlockReport

import org.mockito.Mockito; //导入依赖的package包/类
private void waitForBlockReport(final DatanodeProtocolClientSideTranslatorPB mockNN)
    throws Exception {
  GenericTestUtils.waitFor(new Supplier<Boolean>() {
    @Override
    public Boolean get() {
      try {
        Mockito.verify(mockNN).blockReport(
            Mockito.<DatanodeRegistration>anyObject(),  
            Mockito.eq(FAKE_BPID),
            Mockito.<StorageBlockReport[]>anyObject(),
            Mockito.<BlockReportContext>anyObject());
        return true;
      } catch (Throwable t) {
        LOG.info("waiting on block report: " + t.getMessage());
        return false;
      }
    }
  }, 500, 10000);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:20,代码来源:TestBPOfferService.java

示例15: getSearchFilesEndpoint_should_throw_stockexception_since_the_endpoint_properties_file_is_missing

import org.mockito.Mockito; //导入依赖的package包/类
@Test(groups = "Endpoints.getSearchFilesEndpoint")
public void getSearchFilesEndpoint_should_throw_stockexception_since_the_endpoint_properties_file_is_missing() {
    PowerMockito.spy(Endpoints.class);

    try {
        PowerMockito.doReturn(null).when(Endpoints.class,
                "getResourceAsStream", Mockito.any(String.class));
    } catch (Exception e1) {
        Assert.fail(
                "Couldn't mock the Endpoints.getResourceAsStream method!",
                e1);
    }

    try {
        new Endpoints(Environment.STAGE);

        Assert.fail("Didn't expect the endpoints to get constructed without exception!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(),
                "Could not load the endpoint properties file");
    }
}
 
开发者ID:adobe,项目名称:stock-api-sdk,代码行数:23,代码来源:EndpointsTest.java


注:本文中的org.mockito.Mockito类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。