项目:rskj
文件:TxValidatorMinimumGasPriceValidatorTest.java
@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,BigInteger.valueOf(10),Long.MAX_VALUE,false));
Assert.assertTrue(tvmgpv.validate(tx2,false));
Assert.assertTrue(tvmgpv.validate(tx3,false));
}
项目:hadoop
文件:TestHttpExceptionUtils.java
@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());
}
}
项目:GitHub
文件:ByteBufferGifDecoderTest.java
@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);
}
项目:osc-core
文件:CreatePortGroupTaskTest.java
@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());
}
项目:osc-core
文件:CreatePortGroupTaskTest.java
@Test
public void testExecute_WhenPortGroupIsNotFound_ThrowsException() throws Exception {
// Arrange.
SecurityGroup sg = registerSecurityGroup(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());
}
项目:ysoserial-modified
文件:MyfacesTest.java
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;
}
项目:streamingpool-core
文件:CompositionStreamFactoryTest.java
@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));
}
项目:li-android-sdk-core
文件:LiBaseClientTest.java
@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);
}
项目:stock-api-sdk
文件:SearchCategoryTest.java
@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);
}
}
项目:InfixToObject
文件:InfixToPrefixTest.java
/**
* 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));
}
项目:react-native-call-events
文件:ReactNativeCallEventsModuleTest.java
@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());
}
项目:jira-steps-plugin
文件:EditIssueStepTest.java
@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);
}
项目:oscm
文件:ServiceInstanceTest.java
@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()));
}
项目:hadoop
文件:TestBPOfferService.java
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);
}
项目:stock-api-sdk
文件:EndpointsTest.java
@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");
}
}
private static void setupUploadMock(UploadService mockUploadService) {
String jsonString = "{"
+ "'url' : 'https://s3.amazonaws.com/path',"
+ "'headers' : {"
+ "'Authorization' : 'auth_value',"
+ "'Content-MD5' : 'md5_value',"
+ "'x-amz-content-sha256' : 'sha256_value',"
+ "'x-amz-date' : 'date_value',"
+ "'x-amz-acl' : 'acl_value'"
+ "},"
+ "'location_url' : 'url'"
+ "}";
Gson gson = new Gson();
final UploadResponse response = gson.fromJson(jsonString,UploadResponse.class);
Mockito
.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return Calls.response(response);
}
})
.when(mockUploadService)
.upload(Mockito.<String,RequestBody>anyMap());
}
@Parameters()
public static Collection<Object[]> getTestData() throws EncryptionException {
encryption = Mockito.mock(EncryptionApi.class);
powermockito.mockStatic(StaticRegistry.class);
Mockito.when(StaticRegistry.encryptionApi()).thenReturn(encryption);
Mockito.when(encryption.encryptAESCTR("")).thenReturn(ENCRYPTED_PASSWORD);
return Arrays.asList(new Object[][] {
{UPDATE_OPENSTACK_NO_DEPLOYMENT_SPEC_VS,createOpenstackNoDeploymentSpecGraph(UPDATE_OPENSTACK_NO_DEPLOYMENT_SPEC_VS),false},{UPDATE_OPENSTACK_DEPLOYMENT_SPEC_VS,createOpenstackWithDeploymentSpecGraph(UPDATE_OPENSTACK_DEPLOYMENT_SPEC_VS),{UPDATE_OPENSTACK_LOCK_DEPLOYMENT_SPEC_FAILS_VS,createOpenstacWhenLockingDeploymentSpecFailsGraph(UPDATE_OPENSTACK_LOCK_DEPLOYMENT_SPEC_FAILS_VS),{DELETE_OPENSTACK_WITH_DEPLOYMENT_Specs_VS,createDeleteOpenStackWithDeploymentSpecGraph(DELETE_OPENSTACK_WITH_DEPLOYMENT_Specs_VS),{DELETE_OPENSTACK_WITH_OS_IMAGE_REF_VS,createDeleteOpenStackWithOSImageRefGraph(DELETE_OPENSTACK_WITH_OS_IMAGE_REF_VS),{DELETE_OPENSTACK_WITH_OS_FLAVOR_REF_VS,createDeleteOpenStackWithOSFlavorRefGraph(DELETE_OPENSTACK_WITH_OS_FLAVOR_REF_VS),});
}
项目:oscm
文件:BesDAOTest.java
@Test
public void setUserCredentialsInContext_INTERNAL() {
// given
Map<String,Setting> settings = getSettingsForMode("INTERNAL");
BindingProvider client = Mockito.mock(BindingProvider.class);
Map<String,String> context = new HashMap<>();
Mockito.doReturn(context).when(client).getRequestContext();
// when
besDAO.setUserCredentialsInContext(client,USER,PASSWORD,settings);
// then
assertNull(client.getRequestContext().get(
"username"));
assertNull(client.getRequestContext().get(
"password"));
assertEquals(
USER,client.getRequestContext().get(
BindingProvider.USERNAME_PROPERTY));
assertEquals(
PASSWORD,client.getRequestContext().get(
BindingProvider.PASSWORD_PROPERTY));
}
项目:flink-connectors
文件:FlinkPravegaWriterTest.java
/**
* Tests the close method of the transactional writer.
*/
@Test
public void testTransactionalWriterClose() throws Exception {
try (TransactionalWriterTestContext context = new TransactionalWriterTestContext(PravegaWriterMode.EXACTLY_ONCE)) {
Transaction<Integer> trans = context.prepareTransaction();
try {
try (StreamSinkOperatorTestHarness<Integer> testHarness = createTestHarness(context.sinkFunction)) {
testHarness.open();
// prepare a worst-case situation that exercises the exception handling aspect of close
Mockito.doThrow(new IntentionalRuntimeException()).when(trans).abort();
Mockito.doThrow(new IntentionalRuntimeException()).when(context.pravegaWriter).close();
}
Assert.fail("expected an exception");
} catch (IntentionalRuntimeException e) {
Assert.assertEquals(1,e.getSuppressed().length);
Assert.assertTrue(e.getSuppressed()[0] instanceof IntentionalRuntimeException);
}
// verify that the transaction was aborted and the writer closed
verify(trans).abort();
verify(context.pravegaWriter).close();
}
}
@Test
public void testFailbackToFaultyServiceFails() throws Exception {
DummyHAService svc1 = new DummyHAService(HAServiceState.ACTIVE,svc1Addr);
Mockito.doThrow(new ServiceFailedException("Failed!"))
.when(svc1.proxy).transitionToActive(anyReqInfo());
DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY,svc2Addr);
Mockito.doThrow(new ServiceFailedException("Failed!"))
.when(svc2.proxy).transitionToActive(anyReqInfo());
svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());
try {
doFailover(svc1,svc2,false,false);
fail("Failover to already active service");
} catch (FailoverFailedException ffe) {
// Expected
}
assertEquals(HAServiceState.STANDBY,svc1.state);
assertEquals(HAServiceState.STANDBY,svc2.state);
}
项目:keti
文件:PolicyManagementServiceTest.java
public void testCreatePolicySetsForMultipleZones() {
PolicySet issuer1PolicySet = this.jsonUtils.deserializefromFile("set-with-1-policy.json",PolicySet.class);
PolicySet issuer2PolicySet = this.jsonUtils
.deserializefromFile("policy-set-with-one-policy-one-condition.json",PolicySet.class);
Mockito.when(this.mockZoneResolver.getZoneEntityOrFail()).thenReturn(this.zone1);
this.policyService.upsertPolicySet(issuer1PolicySet);
Mockito.when(this.mockZoneResolver.getZoneEntityOrFail()).thenReturn(this.zone2);
this.policyService.upsertPolicySet(issuer2PolicySet);
Assert.assertEquals(this.policyService.getAllPolicySets().size(),1);
this.policyService.deletePolicySet(issuer2PolicySet.getName());
// need this to delete issuer1PolicySet properly (policy-set-id and
// zone_id are used to find the row)
Mockito.when(this.mockZoneResolver.getZoneEntityOrFail()).thenReturn(this.zone1);
this.policyService.deletePolicySet(issuer1PolicySet.getName());
Assert.assertEquals(this.policyService.getAllPolicySets().size(),0);
}
@Test
public void shouldStopMonitorOnConfigurationChangedIfQueueRemoved() {
this.scheduler.register(this.listenerA1);
this.scheduler.register(this.listenerB1);
Mockito.verify(this.factory).createMonitor(this.executor,this.queueA);
Mockito.verify(this.factory).createMonitor(this.executor,this.queueB);
Mockito.verify(this.monitorA,times(1)).add(this.listenerA1);
Mockito.verify(this.monitorB,times(1)).add(this.listenerB1);
Mockito.when(this.provider.getSqsQueue(UUID_B)).thenReturn(null);
this.scheduler.onConfigurationChanged(new ConfigurationChangedEvent());
Mockito.verifyNoMoreInteractions(this.factory);
Mockito.verify(this.monitorA).getQueue();
Mockito.verify(this.monitorA).isShutDown();
Mockito.verify(this.monitorB).shutDown();
Mockito.verifyNoMoreInteractions(this.monitorA);
Mockito.verifyNoMoreInteractions(this.monitorB);
}
项目:Enjin-Coin-Java-SDK
文件:EventsServiceTest.java
@SuppressWarnings({ "unchecked","serial" })
@Test
public void testGetEvent_AppIdisNull() throws Exception {
GetEventRequestVO getEventRequestVO = ImmutableGetEventRequestVO.builder()
.setAppId((String) null)
.setEventId("eventId")
.setIdentityMap(new HashMap<String,Object>() {{put("uuid","069a79f4-44e9-4726-a5be-fca90e38aaf5");}})
.setAfterEventId("123456789")
.setBeforeEventId("123456789")
.setLimit("50")
.build();
GetEventResponseVO returnedGetEventResponseVO = ImmutableGetEventResponseVO.builder().build();
GetEventResponseVO[] returnedGetEventResponseArray = new GetEventResponseVO[] {returnedGetEventResponseVO};
JsonRpcUtils mockJsonRpcUtils = powermockito.mock(JsonRpcUtils.class);
powermockito.whenNew(JsonRpcUtils.class).withNoArguments().thenReturn(mockJsonRpcUtils);
Mockito.when(mockJsonRpcUtils.sendJsonRpcRequest(Mockito.anyString(),Mockito.any(),Mockito.anyString(),Mockito.isA(Map.class))).thenReturn(returnedGetEventResponseArray);
eventService = new EventsServiceImpl(enjinConfig);
GetEventResponseVO[] getEventResponseVO = eventService.getEvent(getEventRequestVO);
assertthat(getEventResponseVO).isNotNull();
powermockito.verifyNew(JsonRpcUtils.class,Mockito.times(1)).withNoArguments();
Mockito.verify(mockJsonRpcUtils,Mockito.times(1)).sendJsonRpcRequest(Mockito.anyString(),Mockito.isA(Map.class));
}
项目:jmeter-bzm-plugins
文件:HlsSamplerTest.java
@Before
public void setup()
throws Exception {
// TestJMeterUtils.createJmeterEnv();
parserMock = Mockito.mock(Parser.class);
sampler = new HlsSampler();
sampler.setURLData("http://www.mock.com/path");
sampler.setResData("640x360");
sampler.setNetworkData("1395723");
sampler.setBandwidthType("customBandwidth");
sampler.setResolutionType("customresolution");
sampler.setUrlVideoType("Bandwidth");
sampler.setPRotocol("https");
sampler.setPlaySecondsData("20");
sampler.setVideoDuration(true);
sampler.setParser(parserMock);
sampler.setName("Test");
}
项目:Enjin-Coin-Java-SDK
文件:IdentitiesAsyncServiceTest.java
@SuppressWarnings({"unchecked","serial"})
@Test
public void testCreateIdentity_Success() throws Exception {
CreateIdentityRequestVO createIdentityRequestVO = ImmutableCreateIdentityRequestVO.builder()
.setAuth("auth")
.setIdentityMap(new HashMap<String,Object>() {{
put("key","value");
}})
.build();
CreateIdentityResponseVO returnedCreateIdentityResponseVO = ImmutableCreateIdentityResponseVO.builder().build();
JsonRpcUtils mockJsonRpcUtils = powermockito.mock(JsonRpcUtils.class);
powermockito.whenNew(JsonRpcUtils.class).withNoArguments().thenReturn(mockJsonRpcUtils);
Mockito.when(mockJsonRpcUtils.sendJsonRpcRequest(Mockito.anyString(),Mockito.isA(Map.class))).thenReturn(returnedCreateIdentityResponseVO);
identitiesAsyncService = new IdentitiesAsyncServiceImpl(enjinConfig);
CompletableFuture<CreateIdentityResponseVO> createIdentityResponseCompletableFutureVO = identitiesAsyncService.createIdentityAsync(createIdentityRequestVO);
assertthat(createIdentityResponseCompletableFutureVO).isNotNull();
CreateIdentityResponseVO createIdentityResponseVO = createIdentityResponseCompletableFutureVO.get();
assertthat(createIdentityResponseVO).isNotNull();
powermockito.verifyNew(JsonRpcUtils.class,Mockito.isA(Map.class));
}
private static SecurityGroupInterface createsgi(String sgiId,String sgiName,boolean isMarkedForDeletion,String tag,String policyId) {
SecurityGroupInterface sgi = Mockito.mock(SecurityGroupInterface.class);
Mockito.when(sgi.getMgrSecurityGroupInterfaceId()).thenReturn(sgiId);
Mockito.when(sgi.getName()).thenReturn(sgiName);
Mockito.when(sgi.getMarkedForDeletion()).thenReturn(isMarkedForDeletion);
Mockito.when(sgi.getTag()).thenReturn(tag);
Policy policy = Mockito.mock(Policy.class);
Set<Policy> policySet = new HashSet<>();
policySet.add(policy);
Mockito.when(sgi.getMgrPolicies()).thenReturn(policySet);
Mockito.when(policy.getMgrPolicyId()).thenReturn(policyId);
return sgi;
}
项目:server
文件:GenerationTestIT.java
@Test
public void step_3_generate_block() throws Exception {
PeerContext ctx = new PeerContext(GENERATOR,mockTimeProvider);
Block lastBlock = ctx.context.getInstance().getBlockchainService().getLastBlock();
Mockito.when(mockTimeProvider.get()).thenReturn(lastBlock.getTimestamp() + 200);
ctx.generateBlockForNow();
Assert.assertNotEquals("Is new block generated",lastBlock.getID(),ctx.context.getInstance().getBlockchainService().getLastBlock().getID());
Assert.assertFalse("Generator stopped",ctx.context.getInstance().getGenerator().isGenerationAllowed());
Block generatedBlock = ctx.context.getInstance().getBlockchainService()
.getBlock(ctx.context.getInstance().getBlockchainService().getLastBlock().getID());
Assert.assertEquals("DB store new block ID",generatedBlock.getID(),ctx.context.getInstance().getBlockchainService().getLastBlock().getID());
Assert.assertEquals("Period is 180 sec",lastBlock.getTimestamp() + 180,generatedBlock.getTimestamp());
}
项目:hadoop
文件:TestNodesPage.java
@Test
public void testNodesBlockRenderForNodeLabelFilterWithAnyLabel() {
NodesBlock nodesBlock = injector.getInstance(NodesBlock.class);
nodesBlock.set("node.label","*");
nodesBlock.render();
PrintWriter writer = injector.getInstance(PrintWriter.class);
WebAppTests.flushOutput(injector);
Mockito.verify(
writer,Mockito.times(numberOfRacks * numberOfNodesPerRack
* numberOfActualTableHeaders + numberOfThInMetricsTable)).print(
"<td");
}
项目:hadoop
文件:TestActiveStandbyElector.java
/**
* Verify that,when the callback fails to enter active state,after
* a ZK disconnect (i.e from the StatCallback),that the elector rejoins
* the election after sleeping for a short period.
*/
@Test
public void testFailToBecomeActiveAfterZKdisconnect() throws Exception {
mocknopriorActive();
elector.joinElection(data);
Assert.assertEquals(0,elector.sleptFor);
elector.processResult(Code.CONNECTIONLOSS.intValue(),ZK_LOCK_NAME,mockZK,ZK_LOCK_NAME);
Mockito.verify(mockZK,Mockito.times(2)).create(ZK_LOCK_NAME,data,Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL,elector,mockZK);
elector.processResult(Code.NODEEXISTS.intValue(),ZK_LOCK_NAME);
verifyExistCall(1);
Stat stat = new Stat();
stat.setEphemeralOwner(1L);
Mockito.when(mockZK.getSessionId()).thenReturn(1L);
// Fake failure to become active from within the stat callback
Mockito.doThrow(new ServiceFailedException("fail to become active"))
.when(mockApp).becomeActive();
elector.processResult(Code.OK.intValue(),stat);
Mockito.verify(mockApp,Mockito.times(1)).becomeActive();
// should re-join
Mockito.verify(mockZK,Mockito.times(3)).create(ZK_LOCK_NAME,mockZK);
Assert.assertEquals(2,count);
Assert.assertTrue(elector.sleptFor > 0);
}
项目:joal
文件:TrackerClientTest.java
项目:hashsdn-controller
文件:RefreshingSCPModuleInfoRegistryTest.java
@Test
public void testConstructor() throws Exception {
final ModuleInfoRegistry reg = mock(ModuleInfoRegistry.class);
final SchemaContextProvider prov = mock(SchemaContextProvider.class);
doReturn("string").when(prov).toString();
final BundleContext ctxt = mock(BundleContext.class);
final ServiceRegistration<?> servReg = mock(ServiceRegistration.class);
doReturn(servReg).when(ctxt).registerService(any(Class.class),any(SchemaContextProvider.class),any(Dictionary.class));
doReturn(servReg).when(ctxt).registerService(Mockito.anyString(),any(Object.class),any(Dictionary.class));
donothing().when(servReg).setProperties(any(Dictionary.class));
final ClassLoadingStrategy classLoadingStrat = mock(ClassLoadingStrategy.class);
final BindingContextProvider codecRegistryProvider = mock(BindingContextProvider.class);
donothing().when(codecRegistryProvider).update(classLoadingStrat,prov);
final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
doReturn("B-runtime-context").when(bindingRuntimeContext).toString();
doReturn(bindingRuntimeContext).when(codecRegistryProvider).getBindingContext();
final RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg,prov,classLoadingStrat,this.sourceProvider,codecRegistryProvider,ctxt);
donothing().when(servReg).unregister();
final YangModuleInfo modInfo = mock(YangModuleInfo.class);
doReturn("").when(modInfo).toString();
final ObjectRegistration<YangModuleInfo> ymi = mock(ObjectRegistration.class);
doReturn(ymi).when(reg).registerModuleInfo(modInfo);
scpreg.registerModuleInfo(modInfo);
scpreg.updateService();
verify(codecRegistryProvider).update(classLoadingStrat,prov);
scpreg.close();
Mockito.verify(servReg,Mockito.times(1)).setProperties(any(Dictionary.class));
Mockito.verify(servReg,Mockito.times(1)).unregister();
}
项目:hadoop
文件:TestBlockManager.java
private BlockInfoContiguous addBlockOnNodes(long blockId,List<DatanodeDescriptor> nodes) {
BlockCollection bc = Mockito.mock(BlockCollection.class);
Mockito.doReturn((short)3).when(bc).getBlockReplication();
BlockInfoContiguous blockInfo = blockOnNodes(blockId,nodes);
bm.blocksMap.addBlockCollection(blockInfo,bc);
return blockInfo;
}
项目:oscm
文件:SamlKeySelectorTest.java
@Test
public void algorithmCompatibleWithMethod_rsa() {
// given
SamlKeySelector keySelector = mock(SamlKeySelector.class,Mockito.CALLS_REAL_METHODS);
// when
boolean result = keySelector.algorithmCompatibleWithMethod(
SignatureMethod.RSA_SHA1,keySelector.ALGORITHM_RSA);
// then
assertTrue(result);
}
项目:firebase-admin-java
文件:PersistentConnectionTest.java
@Test
public void testOndisconnectCancel() throws InterruptedException {
MockConnectionFactory connFactory = new MockConnectionFactory();
connFactory.persistentConn.onReady(System.currentTimeMillis(),"last-session-id");
connFactory.persistentConn.onDataMessage(
ImmutableMap.<String,Object>of("r",1,"b",ImmutableMap.of("s","ok")));
RequestResultCallback callback = Mockito.mock(RequestResultCallback.class);
connFactory.persistentConn.ondisconnectCancel(ImmutableList.of("put"),callback);
// Write should not be sent until auth us successful
assertEquals(3,connFactory.outgoing.size());
assertEquals("oc",connFactory.outgoing.get(2).getAction());
}
项目:oscm
文件:ServiceProvisioningSuspendResumeServiceTest.java
@Test(expected = OperationNotPermittedException.class)
public void resumeService_CatalogEntriesEmpty() throws Exception {
try {
product.setCatalogEntries(new ArrayList<CatalogEntry>());
bean.resumeService(voService);
} finally {
Mockito.verify(dataServiceMock,Mockito.never()).flush();
}
}
项目:MMORPG_Prototype
文件:LayerCollisionMapTests.java
@Test(expected = OutOfBoundsException.class)
public void insertObjectOnBorder5_5_thenMoveDown_shouldThrowOutOfBoundsException()
{
Mockito
.when(object.getCenter())
.thenReturn(calcPosition(5,5));
collisionMap.insert(object);
collisionMap.moveDown(object);
}
项目:hadoop
文件:TestDFSHAAdmin.java
@Test
public void testFailoverWithFencerConfigured() throws Exception {
Mockito.doReturn(STANDBY_READY_RESULT).when(mockProtocol).getServiceStatus();
HdfsConfiguration conf = getHAConf();
conf.set(DFSConfigKeys.DFS_HA_FENCE_METHODS_KEY,getFencerTrueCommand());
tool.setConf(conf);
assertEquals(0,runTool("-failover","nn1","nn2"));
}
项目:bootstrap
文件:CryptoHelperTest.java
/**
* Test encrypt.
*/
@Test
public void encryptAsNeeded() {
final StringEncryptor stringEncryptor = Mockito.mock(StringEncryptor.class);
Mockito.when(stringEncryptor.decrypt("value")).thenThrow(new EncryptionoperationNotPossibleException());
Mockito.when(stringEncryptor.encrypt("value")).thenReturn("encrypted");
final CryptoHelper securityHelper = new CryptoHelper();
securityHelper.setEncryptor(stringEncryptor);
Assert.assertEquals("encrypted",securityHelper.encryptAsNeeded("value"));
}
项目:osc-core
文件:DeleteServiceFunctionChainServiceTest.java
@Before
public void testinitialize() throws VmidcException {
MockitoAnnotations.initMocks(this);
this.em = InMemDB.getEntityManagerFactory().createEntityManager();
this.txControl.setEntityManager(this.em);
Mockito.when(this.dbMgr.getTransactionalEntityManager()).thenReturn(this.em);
Mockito.when(this.dbMgr.getTransactionControl()).thenReturn(this.txControl);
registerKubernetesPods(this.sgm.getLabel(),MATCHING_PODS);
persist(this.sgm,this.em);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。