Java Examples for org.powermock.api.mockito.PowerMockito
The following java examples will help you to understand the usage of org.powermock.api.mockito.PowerMockito. These source code samples are taken from different open source projects.
Example 1
| Project: XChange-master File: BleutradeExchangeTest.java View source code |
@Test
public void shouldMakeRemoteInit() throws IOException {
// given
List<BleutradeCurrency> currenciesStub = Arrays.asList(createBleutradeCurrency("BTC", "Bitcoin", 2, new BigDecimal("0.00080000"), true, "BITCOIN"), createBleutradeCurrency("LTC", "Litecoin", 4, new BigDecimal("0.02000000"), true, "BITCOIN"));
List<BleutradeMarket> marketsStub = Arrays.asList(createBleutradeMarket("DOGE", "BTC", "Dogecoin", "Bitcoin", new BigDecimal("0.10000000"), "DOGE_BTC", true), createBleutradeMarket("BLEU", "BTC", "Bleutrade Share", "Bitcoin", new BigDecimal("0.00000001"), "BLEU_BTC", true));
BleutradeMarketDataService marketDataServiceMock = mock(BleutradeMarketDataService.class);
PowerMockito.when(marketDataServiceMock.getBleutradeCurrencies()).thenReturn(currenciesStub);
PowerMockito.when(marketDataServiceMock.getBleutradeMarkets()).thenReturn(marketsStub);
Whitebox.setInternalState(exchange, "marketDataService", marketDataServiceMock);
// when
exchange.remoteInit();
// then
Map<Currency, CurrencyMetaData> currencyMetaDataMap = exchange.getExchangeMetaData().getCurrencies();
assertThat(currencyMetaDataMap).hasSize(2);
assertThat(currencyMetaDataMap.get(Currency.BTC).getScale()).isEqualTo(8);
assertThat(currencyMetaDataMap.get(Currency.LTC).getScale()).isEqualTo(8);
Map<CurrencyPair, CurrencyPairMetaData> marketMetaDataMap = exchange.getExchangeMetaData().getCurrencyPairs();
assertThat(marketMetaDataMap).hasSize(2);
// System.out.println(marketMetaDataMap.get(CurrencyPair.DOGE_BTC).toString());
assertThat(marketMetaDataMap.get(CurrencyPair.DOGE_BTC).toString()).isEqualTo("CurrencyPairMetaData [tradingFee=0.0025, minimumAmount=0.10000000, maximumAmount=null, priceScale=8]");
assertThat(marketMetaDataMap.get(BLEU_BTC_CP).toString()).isEqualTo("CurrencyPairMetaData [tradingFee=0.0025, minimumAmount=1E-8, maximumAmount=null, priceScale=8]");
}Example 2
| Project: jenkins-master File: SCMTriggerItemTest.java View source code |
@Test
@Issue("JENKINS-36232")
@PrepareForTest(SCMDecisionHandler.class)
public void noVetoDelegatesPollingToAnSCMedItem() {
// given
PowerMockito.mockStatic(SCMDecisionHandler.class);
PowerMockito.when(SCMDecisionHandler.firstShouldPollVeto(any(Item.class))).thenReturn(null);
SCMedItem scMedItem = Mockito.mock(SCMedItem.class);
TaskListener listener = Mockito.mock(TaskListener.class);
// when
SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(scMedItem).poll(listener);
// then
verify(scMedItem).poll(listener);
}Example 3
| Project: sky-walking-master File: MongoDBWriteBindingInterceptorTest.java View source code |
@Before
public void setUp() throws Exception {
interceptor = new MongoDBWriteBindingInterceptor();
ServerDescription serverDescription = ServerDescription.builder().address(address).state(ServerConnectionState.CONNECTED).build();
PowerMockito.when(connectionSource.getServerDescription()).thenReturn(serverDescription);
PowerMockito.when(writeBinding.getWriteConnectionSource()).thenReturn(connectionSource);
}Example 4
| Project: AndroidFunctionalTester-master File: StartActionTest.java View source code |
@Test
public //Solve Issue with mocking Process Builder
void testSuccess() throws Exception {
Action action = new StartAction();
action.setValues(new Object[] { "XXX" });
//ProcessBuilder pb = PowerMockito.mock(ProcessBuilder.class);
//PowerMockito.whenNew(ProcessBuilder.class).withParameterTypes(String[].class).
// withArguments(anyVararg()).thenReturn(pb);
//when(pb.start()).thenReturn(null);
//PowerMockito.whenNew(ProcessBuilder.class).withParameterTypes(List.class).withArguments(isA(ArrayList.class)).thenReturn(pb);
//Mockito.when(pb.start()).thenReturn(null);
mockStatic(ActionUtils.class);
// Used by message stream
when(ActionUtils.getString(any(InputStream.class))).thenReturn("");
Runtime runtime = Runtime.getRuntime();
Assert.assertNull(action.run(null, runtime));
}Example 5
| Project: jrs-rest-java-client-master File: ExportExecutionRequestBuilderTest.java View source code |
@Test
public void should_send_html_report_asynchronously() throws InterruptedException {
String requestId = "requestId";
String exportId = "exportId";
final AtomicInteger newThreadId = new AtomicInteger();
final int currentThreadId = (int) Thread.currentThread().getId();
ExportExecutionRequestBuilder builderSpy = spy(new ExportExecutionRequestBuilder(sessionStorageMock, requestId, exportId));
PowerMockito.doReturn(reportMock).when(builderSpy).htmlReport(any(ExportDescriptor.class));
final Callback<HtmlReport, Void> callback = spy(new Callback<HtmlReport, Void>() {
@Override
public Void execute(HtmlReport data) {
newThreadId.set((int) Thread.currentThread().getId());
synchronized (this) {
this.notify();
}
return null;
}
});
RequestExecution retrieved = builderSpy.asyncHtmlReport(new ExportDescriptor(), callback);
synchronized (callback) {
callback.wait(1000);
}
assertNotNull(retrieved);
assertNotSame(currentThreadId, newThreadId.get());
Mockito.verify(callback).execute(reportMock);
Mockito.verify(builderSpy).htmlReport(any(ExportDescriptor.class));
}Example 6
| Project: Just-Weather-master File: RxTestUtil.java View source code |
public static void mockRxSchedulers() {
PowerMockito.mockStatic(RxUtil.class);
BDDMockito.given(RxUtil.applyFlowableSchedulers()).willReturn( observable -> observable.subscribeOn(Schedulers.trampoline()).observeOn(Schedulers.trampoline()));
BDDMockito.given(RxUtil.applyMaybeSchedulers()).willReturn( observable -> observable.subscribeOn(Schedulers.trampoline()).observeOn(Schedulers.trampoline()));
BDDMockito.given(RxUtil.applySchedulers()).willReturn( observable -> observable.subscribeOn(Schedulers.trampoline()).observeOn(Schedulers.trampoline()));
BDDMockito.given(RxUtil.applySingleSchedulers()).willReturn( observable -> observable.subscribeOn(Schedulers.trampoline()).observeOn(Schedulers.trampoline()));
}Example 7
| Project: PluginBase-master File: CommandHandlerTest.java View source code |
@Test
public void testCommandDetection() throws Exception {
TestPlugin plugin = PowerMockito.mock(TestPlugin.class);
CommandHandler ch = Mockito.spy(new CommandHandler(plugin) {
{
configureCommandKeys("pb");
configureCommandKeys("pb reload");
}
@Override
protected boolean register(CommandRegistration commandInfo, Command cmd) {
return true;
}
});
String[] res = ch.commandDetection(new String[] { "pb" });
assertEquals(res.length, 1);
assertEquals(res[0], "pb");
res = ch.commandDetection(new String[] { "pb", "reload" });
assertEquals(res.length, 1);
assertEquals(res[0], "pb reload");
res = ch.commandDetection(new String[] { "pb", "reload", "poop" });
assertEquals(res.length, 2);
assertEquals(res[0], "pb reload");
assertEquals(res[1], "poop");
}Example 8
| Project: Signal-Android-master File: BaseUnitTest.java View source code |
@Before
public void setUp() throws Exception {
masterSecret = new MasterSecret(new SecretKeySpec(new byte[16], "AES"), new SecretKeySpec(new byte[16], "HmacSHA1"));
mockStatic(Looper.class);
mockStatic(Log.class);
mockStatic(Handler.class);
mockStatic(TextUtils.class);
mockStatic(PreferenceManager.class);
when(PreferenceManager.getDefaultSharedPreferences(any(Context.class))).thenReturn(sharedPreferences);
when(Looper.getMainLooper()).thenReturn(null);
PowerMockito.whenNew(Handler.class).withAnyArguments().thenReturn(null);
Answer<?> logAnswer = new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
final String tag = (String) invocation.getArguments()[0];
final String msg = (String) invocation.getArguments()[1];
System.out.println(invocation.getMethod().getName().toUpperCase() + "/[" + tag + "] " + msg);
return null;
}
};
PowerMockito.doAnswer(logAnswer).when(Log.class, "d", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "i", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "w", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "e", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "wtf", anyString(), anyString());
PowerMockito.doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
final String s = (String) invocation.getArguments()[0];
return s == null || s.length() == 0;
}
}).when(TextUtils.class, "isEmpty", anyString());
when(sharedPreferences.getString(anyString(), anyString())).thenReturn("");
when(sharedPreferences.getLong(anyString(), anyLong())).thenReturn(0L);
when(sharedPreferences.getInt(anyString(), anyInt())).thenReturn(0);
when(sharedPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(false);
when(sharedPreferences.getFloat(anyString(), anyFloat())).thenReturn(0f);
when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPreferences);
when(context.getPackageName()).thenReturn("org.thoughtcrime.securesms");
}Example 9
| Project: Silence-master File: BaseUnitTest.java View source code |
@Before
public void setUp() throws Exception {
masterSecret = new MasterSecret(new SecretKeySpec(new byte[16], "AES"), new SecretKeySpec(new byte[16], "HmacSHA1"));
mockStatic(Looper.class);
mockStatic(Log.class);
mockStatic(Handler.class);
mockStatic(TextUtils.class);
mockStatic(PreferenceManager.class);
when(PreferenceManager.getDefaultSharedPreferences(any(Context.class))).thenReturn(sharedPreferences);
when(Looper.getMainLooper()).thenReturn(null);
PowerMockito.whenNew(Handler.class).withAnyArguments().thenReturn(null);
Answer<?> logAnswer = new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
final String tag = (String) invocation.getArguments()[0];
final String msg = (String) invocation.getArguments()[1];
System.out.println(invocation.getMethod().getName().toUpperCase() + "/[" + tag + "] " + msg);
return null;
}
};
PowerMockito.doAnswer(logAnswer).when(Log.class, "d", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "i", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "w", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "e", anyString(), anyString());
PowerMockito.doAnswer(logAnswer).when(Log.class, "wtf", anyString(), anyString());
PowerMockito.doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
final String s = (String) invocation.getArguments()[0];
return s == null || s.length() == 0;
}
}).when(TextUtils.class, "isEmpty", anyString());
when(sharedPreferences.getString(anyString(), anyString())).thenReturn("");
when(sharedPreferences.getLong(anyString(), anyLong())).thenReturn(0L);
when(sharedPreferences.getInt(anyString(), anyInt())).thenReturn(0);
when(sharedPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(false);
when(sharedPreferences.getFloat(anyString(), anyFloat())).thenReturn(0f);
when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPreferences);
when(context.getPackageName()).thenReturn("org.smssecure.smssecure");
}Example 10
| Project: CustomShapeImageView-master File: SVGHandlerGradientTransformTest.java View source code |
private void testGradientTransform(String val, Matrix matrix) throws Exception {
//given
when(picture.beginRecording(anyInt(), anyInt())).thenReturn(canvas);
SVGParser.SVGHandler parserHandler = spy(this.parserHandler);
PowerMockito.whenNew(Matrix.class).withArguments(matrix).thenReturn(matrix);
RadialGradient radialGradient = mock(RadialGradient.class);
PowerMockito.whenNew(RadialGradient.class).withArguments(eq(10.0f), eq(10.0f), eq(5.0f), any(int[].class), any(float[].class), eq(Shader.TileMode.CLAMP)).thenReturn(radialGradient);
//when
startSVG(parserHandler);
startElement(parserHandler, attributes(attr("id", "gr1"), attr("cx", "10.0"), attr("cy", "10.0"), attr("r", "5.0"), attr("gradientTransform", val)), "radialGradient");
endElement(parserHandler, "radialGradient");
endSVG(parserHandler);
}Example 11
| Project: jargo-master File: ThrowerTest.java View source code |
@Test
@Ignore("enable when https://github.com/jacoco/jacoco/issues/51 has been fixed")
public void testThatThrowerSpecifiesExceptionAsReturnedToKeepTheCompilerHappyWhenReturnValuesAreRequired() throws Exception {
RuntimeException e = new RuntimeException();
PowerMockito.when(mockedThrower.sneakyThrow(e)).thenReturn(e);
PowerMockito.whenNew(Thrower.class).withAnyArguments().thenReturn(mockedThrower);
Object asUnchecked = Thrower.asUnchecked(e);
assertThat(asUnchecked).isSameAs(e);
}Example 12
| Project: jbpm-master File: JpaSettingsTest.java View source code |
@Test
public void testDefaultJndiName() throws Exception {
// Ensure no persistence-xml is found
when(jpaSettings, PowerMockito.method(JpaSettings.class, "getJndiNameFromPersistenceXml")).withNoArguments().thenReturn(null);
String jndiName = jpaSettings.getDataSourceJndiName();
assertEquals(jndiName, "java:jboss/datasources/ExampleDS");
}Example 13
| Project: jenkins-deployment-dashboard-plugin-master File: EnvironmentDescriptorTest.java View source code |
@BeforeClass
public static void setup() {
server1.setEnvironmentTag(SERVER_TAG);
final ServerEnvironment array[] = { server1 };
final List<ServerEnvironment> ENVS = Arrays.asList(array);
PowerMockito.mockStatic(EC2Connector.class);
when(EC2Connector.getEC2Connector(CREDENTIAL_NAME)).thenReturn(ec2);
when(ec2.getEnvironments(REGION)).thenReturn(ENVS);
}Example 14
| Project: jira-cli-master File: UserTest.java View source code |
@Test
public void testGetUser() throws Exception {
final RestClient restClient = PowerMockito.mock(RestClient.class);
when(restClient.get(anyString(), anyMap())).thenReturn(getTestJSON());
final User user = User.get(restClient, "username");
assertEquals(user.getName(), username);
assertEquals(user.getDisplayName(), displayName);
assertEquals(user.getEmail(), email);
assertEquals(user.getId(), userID);
Map<String, String> avatars = user.getAvatarUrls();
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=16", avatars.get("16x16"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=24", avatars.get("24x24"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=32", avatars.get("32x32"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=48", avatars.get("48x48"));
assertTrue(user.isActive());
}Example 15
| Project: jira-client-master File: UserTest.java View source code |
@Test
public void testGetUser() throws Exception {
final RestClient restClient = PowerMockito.mock(RestClient.class);
when(restClient.get(anyString(), anyMap())).thenReturn(getTestJSON());
final User user = User.get(restClient, "username");
assertEquals(user.getName(), username);
assertEquals(user.getDisplayName(), displayName);
assertEquals(user.getEmail(), email);
assertEquals(user.getId(), userID);
Map<String, String> avatars = user.getAvatarUrls();
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=16", avatars.get("16x16"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=24", avatars.get("24x24"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=32", avatars.get("32x32"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=48", avatars.get("48x48"));
assertTrue(user.isActive());
}Example 16
| Project: jira-rest-java-client-master File: UserTest.java View source code |
@Test
public void testGetUser() throws Exception {
final RestClient restClient = PowerMockito.mock(RestClient.class);
when(restClient.get(anyString(), anyMap())).thenReturn(getTestJSON());
final User user = User.get(restClient, "username");
assertEquals(user.getName(), username);
assertEquals(user.getDisplayName(), displayName);
assertEquals(user.getEmail(), email);
assertEquals(user.getId(), userID);
Map<String, String> avatars = user.getAvatarUrls();
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=16", avatars.get("16x16"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=24", avatars.get("24x24"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=32", avatars.get("32x32"));
assertEquals("https://secure.gravatar.com/avatar/a5a271f9eee8bbb3795f41f290274f8c?d=mm&s=48", avatars.get("48x48"));
assertTrue(user.isActive());
}Example 17
| Project: overlap2d-master File: NewProjectDialogValidatorTest.java View source code |
@Test
public void shouldLogErrorIfTheProjectNameIsInvalid() throws Exception {
given(projectName.getText()).willReturn("endWithSpace ");
boolean validate = validator.validate(stage, projectName);
assertThat(validate, is(false));
given(projectName.getText()).willReturn("");
validate = validator.validate(stage, projectName);
assertThat(validate, is(false));
PowerMockito.verifyStatic(times(3));
}Example 18
| Project: nucleus-master File: NucleusLayoutTest.java View source code |
private void setUpPresenter() throws Exception {
mockPresenter = mock(TestPresenter.class);
PowerMockito.whenNew(Bundle.class).withNoArguments().thenAnswer(new Answer<Bundle>() {
@Override
public Bundle answer(InvocationOnMock invocation) throws Throwable {
return BundleMock.mock();
}
});
mockDelegate = mock(PresenterLifecycleDelegate.class);
PowerMockito.whenNew(PresenterLifecycleDelegate.class).withAnyArguments().thenReturn(mockDelegate);
when(mockDelegate.getPresenter()).thenReturn(mockPresenter);
mockFactory = mock(ReflectionPresenterFactory.class);
when(mockFactory.createPresenter()).thenReturn(mockPresenter);
PowerMockito.mockStatic(ReflectionPresenterFactory.class);
when(ReflectionPresenterFactory.fromViewClass(any(Class.class))).thenReturn(mockFactory);
}Example 19
| Project: ecampus-client-android-master File: SaveBulletinPresenterTest.java View source code |
@Ignore
@Test
public void initializeViewComponent() {
List<Item> subdivisions = getStubSubdivision();
String id = subdivisions.get(0).getId().toString();
PowerMockito.suppress(PowerMockito.constructor(User.class));
User mockUser = PowerMockito.mock(User.class);
PowerMockito.mockStatic(User.class);
doReturn(mockUser).when(Mockito.spy(User.getInstance()));
doReturn(subdivisions).when(mockUser).getSubdivision();
mPresenter.initializeViewComponent();
verify(mView).setViewComponent();
verify(mLoader).loadDescSubdivisions(id);
verify(mLoader).loadGroupsOf(id);
verify(mLoader).loadProfiles();
}Example 20
| Project: gluster-ovirt-poc-master File: VmHandlerTest.java View source code |
@Test
public void UpdateVmGuestAgentVersionWithAppList() {
PowerMockito.mockStatic(Config.class);
Mockito.when(Config.GetValue(ConfigValues.AgentAppName)).thenReturn("oVirt-Agent");
HashMap<String, String> drivers = new HashMap<String, String>();
drivers.put("linux", "xorg-x11-drv-qxl");
Mockito.when(Config.GetValue(ConfigValues.SpiceDriverNameInGuest)).thenReturn(drivers);
VM vm = new VM();
vm.getStaticData().setos(VmOsType.OtherLinux);
vm.setapp_list("kernel-3.0,ovirt-agent-4.5.6,xorg-x11-drv-qxl-0.0.21-3.fc15.i686");
VmHandler.UpdateVmGuestAgentVersion(vm);
Assert.assertNotNull(vm.getGuestAgentVersion());
Assert.assertNotNull(vm.getSpiceDriverVersion());
}Example 21
| Project: pentaho-platform-plugin-reporting-master File: ReservedIdIT.java View source code |
@Test
public void testReserveId() throws Exception {
PowerMockito.mockStatic(PentahoSessionHolder.class);
when(PentahoSessionHolder.getSession()).thenReturn(session);
assertEquals(session, PentahoSessionHolder.getSession());
final JobManager jobManager = new JobManager();
final Response response = jobManager.reserveId();
assertEquals(200, response.getStatus());
assertNotNull(String.valueOf(response.getEntity()).contains("reservedId"));
}Example 22
| Project: react-native-image-picker-master File: ImagePickerModuleTest.java View source code |
private void nativeMock() {
PowerMockito.mockStatic(Arguments.class);
when(Arguments.createArray()).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return new JavaOnlyArray();
}
});
when(Arguments.createMap()).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return new JavaOnlyMap();
}
});
}Example 23
| Project: cytoscape-d3-master File: ActivatorTest.java View source code |
@Test
public void testActivator() throws Exception {
CyActivator activator = new CyActivator();
BundleContext bc = mock(BundleContext.class);
StreamUtil sUtil = mock(StreamUtil.class);
ServiceReference ref = mock(ServiceReference.class);
PowerMockito.when(bc.getServiceReference(StreamUtil.class.getName())).thenReturn(ref);
PowerMockito.when(activator, "getService", bc, StreamUtil.class).thenReturn(sUtil);
activator.start(bc);
}Example 24
| Project: HockeySDK-Android-master File: UpdateManagerTest.java View source code |
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
// Reset Build version code
Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.BASE);
mockContext = mock(Context.class);
mockPackageManager = mock(PackageManager.class);
mockStatic(TextUtils.class);
PowerMockito.when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
CharSequence a = (CharSequence) invocation.getArguments()[0];
return !(a != null && a.length() > 0);
}
});
PowerMockito.when(TextUtils.equals(any(CharSequence.class), any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
CharSequence a = (CharSequence) invocation.getArguments()[0];
CharSequence b = (CharSequence) invocation.getArguments()[1];
return a.equals(b);
}
});
when(mockContext.getPackageManager()).thenReturn(mockPackageManager);
contextWeakReference = new WeakReference<>(mockContext);
}Example 25
| Project: java-odesk-master File: ConfigTest.java View source code |
@Test
public void getProperty() throws Exception {
when(properties.getProperty("key")).thenReturn("value");
final FileInputStream fileInputStreamMock = PowerMockito.mock(FileInputStream.class);
PowerMockito.whenNew(FileInputStream.class).withArguments(Matchers.anyString()).thenReturn(fileInputStreamMock);
Config config = new Config(properties);
String test = config.getProperty("key");
assertEquals("get config property", "value", test);
}Example 26
| Project: java-upwork-master File: ConfigTest.java View source code |
@Test
public void getProperty() throws Exception {
when(properties.getProperty("key")).thenReturn("value");
final FileInputStream fileInputStreamMock = PowerMockito.mock(FileInputStream.class);
PowerMockito.whenNew(FileInputStream.class).withArguments(Matchers.anyString()).thenReturn(fileInputStreamMock);
Config config = new Config(properties);
String test = config.getProperty("key");
assertEquals("get config property", "value", test);
}Example 27
| Project: jetty-runner-master File: JettyRunnerConfigurationTest.java View source code |
@Test
public void testGetConfigurationEditor() throws Exception {
JettyRunnerEditor runEditor = Mockito.mock(JettyRunnerEditor.class);
PowerMockito.whenNew(JettyRunnerEditor.class).withAnyArguments().thenReturn(runEditor);
JettyRunnerConfiguration runnerConf = Whitebox.newInstance(JettyRunnerConfiguration.class);
SettingsEditor<JettyRunnerConfiguration> editor = runnerConf.getConfigurationEditor();
assertNotNull(editor);
PowerMockito.verifyNew(JettyRunnerEditor.class).withArguments(runnerConf);
}Example 28
| Project: mockito-cookbook-master File: BadlyDesignedNewPersonGeneratorPowerMockTestNgTest.java View source code |
@Test
public void should_return_person_with_new_identity() throws Exception {
// given
List<Person> siblings = asList(new Person("John", 10), new Person("Maria", 12));
Person person = new Person("Robert", 25, siblings);
NewIdentityCreator newIdentityCreator = Mockito.mock(NewIdentityCreator.class);
PowerMockito.whenNew(NewIdentityCreator.class).withAnyArguments().thenReturn(newIdentityCreator);
// when
Person newPerson = systemUnderTest.generateNewIdentity(person);
// then
then(newPerson).isNotEqualTo(person);
then(newPerson.getAge()).isNotEqualTo(person.getAge());
then(newPerson.getName()).isNotEqualTo(person.getName());
then(newPerson.getSiblings()).doesNotContainAnyElementsOf(siblings);
}Example 29
| Project: PeerWasp-master File: RemoteAddLocalExists.java View source code |
@Test
public void conflict() throws Exception {
PowerMockito.mockStatic(ConflictHandler.class);
local.put(filePath, file2);
localDatabase.put(filePath, file2);
remote.put(filePath, file1);
listSync.sync(local, localDatabase, remote, remoteDatabase);
PowerMockito.stub(PowerMockito.method(ConflictHandler.class, "rename")).toReturn(Paths.get("asdf"));
PowerMockito.verifyStatic();
ConflictHandler.resolveConflict(Matchers.any(Path.class));
Mockito.verifyNoMoreInteractions(fileEventManager);
}Example 30
| Project: rdp4j-master File: ParallelPollerTest.java View source code |
@Test
public void singleThreadExecutor() throws Exception {
// given
PowerMockito.mockStatic(Executors.class);
DirectoryPoller dp = Mockito.mock(DirectoryPoller.class);
dp.directories = new HashSet<PolledDirectory>();
dp.parallelDirectoryPollingEnabled = false;
// when
pollerTask = new ScheduledRunnable(dp);
// then
PowerMockito.verifyStatic();
Executors.newSingleThreadExecutor();
}Example 31
| Project: sling-master File: ConcurrentJcrResourceBundleLoadingTest.java View source code |
@Before
public void setup() throws Exception {
provider = spy(new JcrResourceBundleProvider());
provider.activate(PowerMockito.mock(BundleContext.class), new JcrResourceBundleProvider.Config() {
@Override
public Class<? extends Annotation> annotationType() {
return JcrResourceBundleProvider.Config.class;
}
@Override
public boolean preload_bundles() {
return false;
}
@Override
public String locale_default() {
return "en";
}
@Override
public long invalidation_delay() {
return 5000;
}
});
doReturn(english).when(provider, "createResourceBundle", eq(null), eq(Locale.ENGLISH));
doReturn(german).when(provider, "createResourceBundle", eq(null), eq(Locale.GERMAN));
Mockito.when(german.getLocale()).thenReturn(Locale.GERMAN);
Mockito.when(english.getLocale()).thenReturn(Locale.ENGLISH);
Mockito.when(german.getParent()).thenReturn(english);
}Example 32
| Project: spring-data-solr-examples-master File: LocaleContextHolderWrapperTest.java View source code |
@Test
public void getCurrentLocale_ShouldReturnCorrectLocale() {
PowerMockito.mockStatic(LocaleContextHolder.class);
when(LocaleContextHolder.getLocale()).thenReturn(Locale.US);
Locale currentLocale = localeContextHolderWrapper.getCurrentLocale();
PowerMockito.verifyStatic(times(1));
LocaleContextHolder.getLocale();
assertEquals(Locale.US, currentLocale);
}Example 33
| Project: uaiMockServer-master File: XmlUnitWrapperExceptionTest.java View source code |
@Test
public void isHandlingSAXException() throws NoSuchFieldException, IllegalAccessException, IOException, SAXException {
PowerMockito.when(XMLUnit.compareXML(Mockito.anyString(), Mockito.anyString())).thenThrow(new SAXException());
try {
XmlUnitWrapper.isIdentical("<a></a>", "<a></a>");
fail("An Exception should happen");
} catch (IllegalArgumentException ex) {
assertEquals(ex.getCause().getClass(), SAXException.class);
}
}Example 34
| Project: asciidoclet-master File: StandardAdapterTest.java View source code |
@Test
public void testValidOptions() throws Exception {
DocErrorReporter mockReporter = mock(DocErrorReporter.class);
String[][] options = new String[][] { { "test" } };
PowerMockito.when(Standard.class, "validOptions", options, mockReporter).thenReturn(true);
assertTrue(adapter.validOptions(options, mockReporter));
PowerMockito.verifyStatic();
Standard.validOptions(options, mockReporter);
}Example 35
| Project: RxLocation-master File: SettingsTest.java View source code |
@Test
public void Check_LocationRequest() throws Exception {
ArgumentCaptor<SettingsCheckSingleOnSubscribe> captor = ArgumentCaptor.forClass(SettingsCheckSingleOnSubscribe.class);
doReturn(locationSettingsRequestBuilder).when(locationSettingsRequestBuilder).addLocationRequest(locationRequest);
doReturn(locationSettingsRequest).when(locationSettingsRequestBuilder).build();
LocationSettings settings = spy(rxLocation.settings());
doReturn(locationSettingsRequestBuilder).when(settings).getLocationSettingsRequestBuilder();
settings.check(locationRequest);
settings.check(locationRequest, TIMEOUT_TIME, TIMEOUT_TIMEUNIT);
PowerMockito.verifyStatic(times(2));
Single.create(captor.capture());
SettingsCheckSingleOnSubscribe single = captor.getAllValues().get(0);
assertEquals(locationSettingsRequest, single.locationSettingsRequest);
assertNoTimeoutSet(single);
single = captor.getAllValues().get(1);
assertEquals(locationSettingsRequest, single.locationSettingsRequest);
assertTimeoutSet(single);
}Example 36
| Project: gerrit-trigger-plugin-master File: SpecGerritVerifiedSetterTest.java View source code |
/**
* Prepare all the mocks.
*
* @throws Exception if so
*/
@Before
public void setUp() throws Exception {
hudson = PowerMockito.mock(Hudson.class);
when(hudson.getRootUrl()).thenReturn("http://localhost/");
PowerMockito.mockStatic(GerritMessageProvider.class);
when(GerritMessageProvider.all()).thenReturn(null);
taskListener = mock(TaskListener.class);
mockGerritCmdRunner = mock(GerritCmdRunner.class);
build = mock(AbstractBuild.class);
env = Setup.createEnvVars();
when(build.getEnvironment(taskListener)).thenReturn(env);
when(build.getId()).thenReturn("1");
project = mock(AbstractProject.class);
doReturn("MockProject").when(project).getFullName();
when(build.getProject()).thenReturn(project);
when(build.getParent()).thenReturn(project);
doReturn(build).when(project).getBuild(anyString());
trigger = mock(GerritTrigger.class);
when(trigger.getGerritBuildSuccessfulCodeReviewValue()).thenReturn(null);
when(trigger.getGerritBuildSuccessfulVerifiedValue()).thenReturn(null);
when(trigger.getGerritBuildFailedCodeReviewValue()).thenReturn(null);
when(trigger.getGerritBuildFailedVerifiedValue()).thenReturn(null);
Setup.setTrigger(trigger, project);
mockStatic(Jenkins.class);
jenkins = mock(Jenkins.class);
when(Jenkins.getInstance()).thenReturn(jenkins);
when(jenkins.getItemByFullName(eq("MockProject"), same(AbstractProject.class))).thenReturn(project);
when(jenkins.getItemByFullName(eq("MockProject"), same(Job.class))).thenReturn(project);
mockStatic(GerritTriggeredBuildListener.class);
when(GerritTriggeredBuildListener.all()).thenReturn(mock(ExtensionList.class));
}Example 37
| Project: aeolus-master File: FileOutputBoltTest.java View source code |
@Test
public void testExecute() throws Exception {
final LinkedList<String> expectedResult = new LinkedList<String>();
final LinkedList<String> result = new LinkedList<String>();
final LinkedList<Tuple> input = new LinkedList<Tuple>();
Config conf = new Config();
String dummyDir = "dummyDir";
String dummyFile = "dummyFile";
String usedDir = ".";
String usedFile = "result.dat";
switch(this.r.nextInt(4)) {
case 0:
conf.put(TestFileOutputBolt.OUTPUT_DIR_NAME, dummyDir);
usedDir = dummyDir;
break;
case 1:
conf.put(TestFileOutputBolt.OUTPUT_FILE_NAME, dummyFile);
usedFile = dummyFile;
break;
case 2:
conf.put(TestFileOutputBolt.OUTPUT_DIR_NAME, dummyDir);
conf.put(TestFileOutputBolt.OUTPUT_FILE_NAME, dummyFile);
usedDir = dummyDir;
usedFile = dummyFile;
break;
default:
}
FileWriter fileWriterMock = PowerMockito.mock(FileWriter.class);
PowerMockito.whenNew(FileWriter.class).withArguments(usedDir + File.separator + usedFile).thenReturn(fileWriterMock);
BufferedWriter dummyWriter = new BufferedWriter(fileWriterMock) {
@Override
public void write(String s) {
result.add(s);
}
};
PowerMockito.whenNew(BufferedWriter.class).withArguments(fileWriterMock).thenReturn(dummyWriter);
TestFileOutputBolt bolt = new TestFileOutputBolt();
TestOutputCollector collector = new TestOutputCollector();
bolt.prepare(conf, null, new OutputCollector(collector));
GeneralTopologyContext context = mock(GeneralTopologyContext.class);
when(context.getComponentOutputFields(anyString(), anyString())).thenReturn(new Fields("dummy"));
when(context.getComponentId(anyInt())).thenReturn("componentID");
final int numberOfLines = 20;
for (int i = 0; i < numberOfLines; ++i) {
TupleImpl t = new TupleImpl(context, new Values(new Integer(this.r.nextInt())), 0, null);
input.add(t);
expectedResult.add(t.toString());
bolt.execute(t);
}
Assert.assertEquals(expectedResult, result);
Assert.assertEquals(input, collector.acked);
}Example 38
| Project: brave-master File: PlatformTest.java View source code |
static void nicWithAddress(@Nullable InetAddress address) throws SocketException {
mockStatic(NetworkInterface.class);
Vector<InetAddress> addresses = new Vector<>();
if (address != null)
addresses.add(address);
NetworkInterface nic = PowerMockito.mock(NetworkInterface.class);
Vector<NetworkInterface> nics = new Vector<>();
nics.add(nic);
when(NetworkInterface.getNetworkInterfaces()).thenReturn(nics.elements());
when(nic.getInetAddresses()).thenReturn(addresses.elements());
}Example 39
| Project: elmis-master File: RestPODControllerTest.java View source code |
@Test
public void shouldSavePOD() throws Exception {
OrderPOD orderPod = new OrderPOD();
when(principal.getName()).thenReturn("2");
doNothing().when(restPODService).updatePOD(orderPod, 2L);
ResponseEntity<RestResponse> response = new ResponseEntity<>(new RestResponse(SUCCESS, "success"), OK);
PowerMockito.when(success("message.success.pod.updated")).thenReturn(response);
ResponseEntity<RestResponse> responseEntity = controller.savePOD(orderPod, "ON123", principal);
assertThat(responseEntity.getBody().getSuccess(), is("success"));
verify(restPODService).updatePOD(orderPod, 2L);
}Example 40
| Project: gerrit-events-master File: AbstractSendCommandJob2Test.java View source code |
/**
* Tests {@link sendCommand()}.
*
* @throws IOException if so.
*/
@Test
public void testSendCommand() throws IOException {
SshConnection mockSshConnection = mock(SshConnection.class);
when(mockSshConnection.executeCommand(anyString())).thenReturn("OK");
PowerMockito.mockStatic(SshConnectionFactory.class);
when(SshConnectionFactory.getConnection(anyString(), anyInt(), anyString(), (Authentication) anyObject())).thenReturn(mockSshConnection);
AbstractSendCommandJob2 job = new AbstractSendCommandJob2Impl(mockConfig);
Assert.assertThat(job.call(), containsString("OK"));
Mockito.verify(mockSshConnection).executeCommand(anyString());
Mockito.verify(mockSshConnection).disconnect();
}Example 41
| Project: jmeter-plugins-master File: HueRotateTest.java View source code |
/**
* Test factory retrieves huerotate with null options
*/
@Test
public void testFactoryNullPaletteNull() {
PowerMockito.mockStatic(JMeterUtils.class);
PowerMockito.when(JMeterUtils.getProperty("jmeterPlugin.customColorsDispatcher")).thenReturn("huerotate");
PowerMockito.when(JMeterUtils.getProperty("jmeterPlugin.customColorsDispatcher.options")).thenReturn(null);
ColorsDispatcher instance = ColorsDispatcherFactory.getColorsDispatcher();
PowerMockito.verifyStatic();
assertEquals("HueRotatePalette", instance.getClass().getSimpleName());
}Example 42
| Project: openshop.io-android-master File: SettingsMyUnitTest.java View source code |
@Before
public void preparation() throws Exception {
// for case them used another runner
MockitoAnnotations.initMocks(this);
PowerMockito.spy(SettingsMy.class);
PowerMockito.doReturn(mockSharedPreferences).when(SettingsMy.class, "getSettings");
Whitebox.setInternalState(SettingsMy.class, "actualShop", (Object[]) null);
Whitebox.setInternalState(SettingsMy.class, "activeUser", (Object[]) null);
}Example 43
| Project: device-year-class-master File: YearClassTest.java View source code |
private int getYearClass(int numCores, int maxFreqKHz, long memoryBytes) {
mockStatic(DeviceInfo.class);
when(DeviceInfo.getNumberOfCPUCores()).thenReturn(numCores);
when(DeviceInfo.getCPUMaxFreqKHz()).thenReturn(maxFreqKHz);
when(DeviceInfo.getTotalMemory((Context) any())).thenReturn(memoryBytes);
int yearClass = YearClass.get(null);
PowerMockito.verifyStatic();
return yearClass;
}Example 44
| Project: js-android-sdk-master File: ServerInfoTransformerTest.java View source code |
@Before
public void setup() {
transformerUnderTest = ServerInfoTransformer.get();
mServerInfoData = PowerMockito.mock(ServerInfoData.class);
when(mServerInfoData.getBuild()).thenReturn("20150527_1447");
when(mServerInfoData.getDateFormatPattern()).thenReturn("yyyy-MM-dd");
when(mServerInfoData.getDatetimeFormatPattern()).thenReturn("yyyy-MM-dd'T'HH:mm:ss");
when(mServerInfoData.getVersion()).thenReturn("6.1");
when(mServerInfoData.getEdition()).thenReturn("PRO");
when(mServerInfoData.getEditionName()).thenReturn("Enterprise for AWS");
when(mServerInfoData.getFeatures()).thenReturn("Fusion");
when(mServerInfoData.getLicenseType()).thenReturn("Type");
}Example 45
| Project: openshift-deployer-plugin-master File: ExpandedJenkinsVarsTest.java View source code |
@Before
public void setup() throws Exception {
// Setup Mocks
PowerMockito.mockStatic(Jenkins.class);
PowerMockito.when(Jenkins.getInstance()).thenReturn(jenkins);
final ExtensionList extensionList = mock(ExtensionList.class);
when(extensionList.toArray()).thenReturn(new Object[] {});
//noinspection unchecked
when(jenkins.getExtensionList(TokenMacro.class)).thenReturn(extensionList);
when(build.getEnvironment(listener)).thenReturn(new EnvVars(ENVVAR_KEY_GIT_BRANCH, ENVVAR_VALUE_GIT_BRANCH));
mockStatic(Computer.class);
PowerMockito.when(Computer.currentComputer()).thenReturn(mock(MasterComputer.class));
}Example 46
| Project: RxDownloadManager-master File: DownloadIdToUriTest.java View source code |
@Test
public void call_downloadSuccess() throws Exception {
when(cursor.moveToFirst()).thenReturn(true);
when(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)).thenReturn(15);
when(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)).thenReturn(16);
when(cursor.getInt(15)).thenReturn(DownloadManager.STATUS_SUCCESSFUL);
when(cursor.getString(16)).thenReturn("file");
when(dm.query((DownloadManager.Query) any())).thenReturn(cursor);
mockStatic(Uri.class);
PowerMockito.when(Uri.parse("file")).thenReturn(Uri.EMPTY);
assertThat(func.call(1L), is(Uri.EMPTY));
}Example 47
| Project: alluxio-master File: AlluxioLineageTest.java View source code |
@Before
public void before() throws Exception {
Configuration.set(PropertyKey.USER_LINEAGE_ENABLED, "true");
mLineageMasterClient = PowerMockito.mock(LineageMasterClient.class);
mLineageContext = PowerMockito.mock(LineageContext.class);
Mockito.when(mLineageContext.acquireMasterClient()).thenReturn(mLineageMasterClient);
mAlluxioLineage = AlluxioLineage.get(mLineageContext);
}Example 48
| Project: anaplan-mulesoft-master File: AnaplanUtilTestCases.java View source code |
@Test
public void testRunServerTask() throws Exception {
final int mockServerPingCountLimit = 4;
PowerMockito.doReturn(mockTaskStatus).when(mockTask).getStatus();
PowerMockito.doReturn(TaskStatus.State.IN_PROGRESS).when(mockTaskStatus).getTaskState();
Mockito.when(mockTaskStatus.getTaskState()).thenAnswer(new Answer() {
private int count = 0;
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
if (count++ < mockServerPingCountLimit)
return TaskStatus.State.IN_PROGRESS;
return TaskStatus.State.COMPLETE;
}
});
TaskStatus resultStatus = AnaplanUtil.runServerTask(mockTask);
assertEquals(mockTaskStatus, resultStatus);
}Example 49
| Project: ArcGIS-Server-SOS-Extension-master File: PropertyUnitMappingCacheTest.java View source code |
@Test
public void testSerializationRoundtrip() throws IOException, CacheException {
PowerMockito.mockStatic(CommonUtilities.class);
File f = File.createTempFile("hassss", "da");
f.mkdir();
BDDMockito.given(CommonUtilities.resolveCacheBaseDir("test")).willReturn(f.getParentFile());
PropertyUnitMappingCache pumc = PropertyUnitMappingCache.instance("test");
Map<String, PropertyUnitMapping> result = pumc.deserializeEntityCollection(new ByteArrayInputStream(line.getBytes()));
PropertyUnitMapping mapping = result.values().iterator().next();
Assert.assertTrue("Unexpected mapping size", 12 == mapping.size());
String roundtripped = "0=".concat(pumc.serializeEntity(mapping));
Map<String, PropertyUnitMapping> resultRoundtripped = pumc.deserializeEntityCollection(new ByteArrayInputStream(roundtripped.getBytes()));
PropertyUnitMapping mappingRoundtripped = resultRoundtripped.values().iterator().next();
Assert.assertEquals(mapping, mappingRoundtripped);
}Example 50
| Project: async-http-client-master File: ResumableRandomAccessFileListenerTest.java View source code |
@Test
public void testOnBytesReceivedBufferHasArray() throws IOException {
RandomAccessFile file = PowerMockito.mock(RandomAccessFile.class);
ResumableRandomAccessFileListener listener = new ResumableRandomAccessFileListener(file);
byte[] array = new byte[] { 1, 2, 23, 33 };
ByteBuffer buf = ByteBuffer.wrap(array);
listener.onBytesReceived(buf);
verify(file).write(array, 0, 4);
}Example 51
| Project: AwesomeValidation-master File: TextInputLayoutValidatorTest.java View source code |
public void testValidationCallbackExecute() {
ValidationCallback validationCallback = Whitebox.getInternalState(mSpiedTextInputLayoutValidator, "mValidationCallback");
Matcher mockMatcher = PowerMockito.mock(Matcher.class);
TextInputLayout mockTextInputLayout = mock(TextInputLayout.class);
String mockErrMsg = PowerMockito.mock(String.class);
when(mMockValidationHolder.getTextInputLayout()).thenReturn(mockTextInputLayout);
when(mMockValidationHolder.getErrMsg()).thenReturn(mockErrMsg);
validationCallback.execute(mMockValidationHolder, mockMatcher);
verify(mockTextInputLayout).setErrorEnabled(true);
verify(mockTextInputLayout).setError(mockErrMsg);
}Example 52
| Project: BetterBatteryStats-master File: GraphSerieTest.java View source code |
@Test
public void testGraphSerie() throws Exception {
PowerMockito.mockStatic(Log.class);
ArrayList<Datapoint> nullSerie = null;
ArrayList<Datapoint> emptySerie = new ArrayList();
ArrayList<Datapoint> serie = new ArrayList();
// populate serie
for (int i = 0; i < 1000; i++) {
serie.add(new Datapoint(i, 1000 - i));
}
GraphSerie gs1 = new GraphSerie("gs1", nullSerie);
GraphSerie gs2 = new GraphSerie("gs2", emptySerie);
GraphSerie gs3 = new GraphSerie("gs3", serie);
assertTrue(gs1.size() == 0);
assertTrue(gs2.size() == 0);
assertTrue(gs3.size() > 0);
assertTrue(gs1.getTitle().equals("gs1"));
assertTrue(gs2.getTitle().equals("gs2"));
assertTrue(gs3.getTitle().equals("gs3"));
// we expect the GraphSerie to have detected and replaced the empty array
assertFalse(gs1.getValues() == nullSerie);
assertTrue(gs2.getValues() == emptySerie);
assertTrue(gs3.getValues() == serie);
}Example 53
| Project: cloudbreak-master File: SaltOrchestratorTest.java View source code |
@Before
public void setUp() throws Exception {
gatewayConfig = new GatewayConfig("1.1.1.1", "10.0.0.1", "172.16.252.43", "10-0-0-1", 9443, "/certdir", "servercert", "clientcert", "clientkey", "saltpasswd", "saltbootpassword", "signkey", false, true, null, null);
targets = new HashSet<>();
targets.add(new Node("10.0.0.1", "1.1.1.1", "10-0-0-1.example.com"));
targets.add(new Node("10.0.0.2", "1.1.1.2", "10-0-0-2.example.com"));
targets.add(new Node("10.0.0.3", "1.1.1.3", "10-0-0-3.example.com"));
saltConnector = mock(SaltConnector.class);
PowerMockito.whenNew(SaltConnector.class).withAnyArguments().thenReturn(saltConnector);
parallelOrchestratorComponentRunner = mock(ParallelOrchestratorComponentRunner.class);
when(parallelOrchestratorComponentRunner.submit(any())).thenReturn(CompletableFuture.completedFuture(true));
when(hostDiscoveryService.determineDomain()).thenReturn(".example.com");
exitCriteria = mock(ExitCriteria.class);
exitCriteriaModel = mock(ExitCriteriaModel.class);
}Example 54
| Project: contrail-vcenter-plugin-master File: VCenterDBTest.java View source code |
@Before
public void globalSetUp() throws IOException {
// Setup VCenter object
vcenterDB = new VCenterDB("https://10.20.30.40/sdk", "admin", "admin123", "unittest_dc", "unittest_dvs", "unittest_fabric_pg", Mode.VCENTER_ONLY);
vncDB = mock(VncDB.class);
doNothing().when(vncDB).createVirtualNetwork(any(VirtualNetworkInfo.class));
doNothing().when(vncDB).createVirtualMachine(any(VirtualMachineInfo.class));
doNothing().when(vncDB).createVirtualMachineInterface(any(VirtualMachineInterfaceInfo.class));
doNothing().when(vncDB).createInstanceIp(any(VirtualMachineInterfaceInfo.class));
doNothing().when(vncDB).deleteVirtualNetwork(any(VirtualNetworkInfo.class));
doNothing().when(vncDB).deleteVirtualMachine(any(VirtualMachineInfo.class));
doNothing().when(vncDB).deleteVirtualMachineInterface(any(VirtualMachineInterfaceInfo.class));
doNothing().when(vncDB).deleteInstanceIp(any(VirtualMachineInterfaceInfo.class));
PowerMockito.mockStatic(VRouterNotifier.class);
}Example 55
| Project: ddf-master File: TestPepInterceptorNullAssertionToken.java View source code |
@Test
public void testMessageNullSecurityAssertionToken() {
PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();
Message messageWithNullSecurityAssertion = mock(Message.class);
SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);
assertNotNull(mockSecurityAssertion);
PowerMockito.mockStatic(SecurityAssertionStore.class);
PowerMockito.mockStatic(SecurityLogger.class);
when(SecurityAssertionStore.getSecurityAssertion(messageWithNullSecurityAssertion)).thenReturn(mockSecurityAssertion);
// SecurityLogger is already stubbed out
when(mockSecurityAssertion.getSecurityToken()).thenReturn(null);
expectedExForNullMessage.expect(AccessDeniedException.class);
expectedExForNullMessage.expectMessage("Unauthorized");
interceptor.handleMessage(messageWithNullSecurityAssertion);
PowerMockito.verifyStatic();
}Example 56
| Project: ddf-platform-master File: TestPepInterceptorNullAssertionToken.java View source code |
@Test
public void testMessageNullSecurityAssertionToken() {
PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();
Message messageWithNullSecurityAssertion = mock(Message.class);
SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);
assertNotNull(mockSecurityAssertion);
PowerMockito.mockStatic(SecurityAssertionStore.class);
PowerMockito.mockStatic(SecurityLogger.class);
when(SecurityAssertionStore.getSecurityAssertion(messageWithNullSecurityAssertion)).thenReturn(mockSecurityAssertion);
// SecurityLogger is already stubbed out
when(mockSecurityAssertion.getSecurityToken()).thenReturn(null);
expectedExForNullMessage.expect(AccessDeniedException.class);
expectedExForNullMessage.expectMessage("Unauthorized");
interceptor.handleMessage(messageWithNullSecurityAssertion);
PowerMockito.verifyStatic();
}Example 57
| Project: deadcode4j-master File: A_SpringNamespaceHandlerAnalyzer.java View source code |
@Test
public void handlesIOExceptionWhenAnalyzingFile() throws Exception {
Properties mock = Mockito.mock(Properties.class);
doThrow(new IOException("JUnit")).when(mock).load(Mockito.any(InputStream.class));
PowerMockito.whenNew(Properties.class).withNoArguments().thenReturn(mock);
try {
analyzeFile(SPRING_HANDLER_FILE);
fail("Should abort analysis!");
} catch (RuntimeException e) {
assertThat(e.getMessage(), containsString(SPRING_HANDLER_FILE));
}
}Example 58
| Project: email-ext-plugin-master File: DevelopersRecipientProviderTest.java View source code |
@Before
public void before() throws Exception {
final Jenkins jenkins = PowerMockito.mock(Jenkins.class);
PowerMockito.when(jenkins.isUseSecurity()).thenReturn(false);
final ExtendedEmailPublisherDescriptor extendedEmailPublisherDescriptor = PowerMockito.mock(ExtendedEmailPublisherDescriptor.class);
extendedEmailPublisherDescriptor.setDebugMode(true);
PowerMockito.when(extendedEmailPublisherDescriptor.getExcludedCommitters()).thenReturn("");
PowerMockito.when(jenkins.getDescriptorByType(ExtendedEmailPublisherDescriptor.class)).thenReturn(extendedEmailPublisherDescriptor);
PowerMockito.mockStatic(Jenkins.class);
PowerMockito.doReturn(jenkins).when(Jenkins.class, "getActiveInstance");
final Mailer.DescriptorImpl descriptor = PowerMockito.mock(Mailer.DescriptorImpl.class);
PowerMockito.when(descriptor.getDefaultSuffix()).thenReturn("DOMAIN");
PowerMockito.mockStatic(Mailer.class);
PowerMockito.doReturn(descriptor).when(Mailer.class, "descriptor");
}Example 59
| Project: facebook-android-sdk-master File: AccessTokenCacheTest.java View source code |
@Before
public void before() throws Exception {
mockStatic(FacebookSdk.class);
sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(AccessTokenManager.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
sharedPreferences.edit().clear().commit();
cachingStrategyFactory = mock(AccessTokenCache.SharedPreferencesTokenCachingStrategyFactory.class);
when(cachingStrategyFactory.create()).thenReturn(cachingStrategy);
stub(PowerMockito.method(Utility.class, "awaitGetGraphMeRequestWithCache")).toReturn(new JSONObject().put("id", "1000"));
}Example 60
| Project: graceland-core-master File: NativePluginLoaderTest.java View source code |
@Test
public void gets_plugins_from_serviceloader() {
Plugin plugin1 = mock(Plugin.class);
Plugin plugin2 = mock(Plugin.class);
Plugin plugin3 = mock(Plugin.class);
ServiceLoader dummyLoader = PowerMockito.mock(ServiceLoader.class);
when(dummyLoader.iterator()).thenReturn(ImmutableList.of(plugin1, plugin2, plugin3).iterator());
PowerMockito.mockStatic(ServiceLoader.class);
when(ServiceLoader.load(any(Class.class))).thenReturn(dummyLoader);
pluginLoader.loadInto(application);
verify(application).loadPlugin(eq(plugin1));
verify(application).loadPlugin(eq(plugin2));
verify(application).loadPlugin(eq(plugin3));
}Example 61
| Project: hawkular-inventory-master File: ConfigurationPassingTest.java View source code |
@Test
public void testConfigurationPassing() throws Exception {
PowerMockito.mockStatic(System.class);
Mockito.when(System.getenv("HAWKULAR_INVENTORY_SQL_JDBC_URL")).thenReturn("kachny");
try {
new SqlGraphProvider().instantiateGraph(Configuration.builder().addConfigurationProperty("sql.jdbc.url", "voe").build());
Assert.fail("Should not be possible to instantiate graph with invalid jdbc url");
} catch (Exception e) {
Assert.assertTrue(e.getCause().getMessage().contains("kachny"));
}
}Example 62
| Project: java-util-master File: TestInetAddressUnknownHostException.java View source code |
@Test
public void testGetIpAddressWithUnkownHost() throws Exception {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException());
Assert.assertArrayEquals(new byte[] { 0, 0, 0, 0 }, InetAddressUtilities.getIpAddress());
Assert.assertEquals("localhost", InetAddressUtilities.getHostName());
}Example 63
| Project: jbosstools-openshift-master File: ProjectWrapperTest.java View source code |
@Before
public void initilize() {
watchManager = mock(WatchManager.class);
PowerMockito.mockStatic(WatchManager.class);
PowerMockito.when(WatchManager.getInstance()).thenReturn(watchManager);
this.connection = mock(IOpenShiftConnection.class);
this.connectionWrapper = new ConnectionWrapper(mock(OpenshiftUIModel.class), connection);
this.project = mock(IProject.class);
when(project.getNamespace()).thenReturn("namespace");
this.projectWrapper = new ProjectWrapper(connectionWrapper, project);
}Example 64
| Project: jenkins-plugins-master File: DevelopersRecipientProviderTest.java View source code |
@Before
public void before() throws Exception {
final Jenkins jenkins = PowerMockito.mock(Jenkins.class);
PowerMockito.when(jenkins.isUseSecurity()).thenReturn(false);
final ExtendedEmailPublisherDescriptor extendedEmailPublisherDescriptor = PowerMockito.mock(ExtendedEmailPublisherDescriptor.class);
extendedEmailPublisherDescriptor.setDebugMode(true);
PowerMockito.when(extendedEmailPublisherDescriptor.getExcludedCommitters()).thenReturn("");
PowerMockito.when(jenkins.getDescriptorByType(ExtendedEmailPublisherDescriptor.class)).thenReturn(extendedEmailPublisherDescriptor);
PowerMockito.mockStatic(Jenkins.class);
PowerMockito.doReturn(jenkins).when(Jenkins.class, "getActiveInstance");
final Mailer.DescriptorImpl descriptor = PowerMockito.mock(Mailer.DescriptorImpl.class);
PowerMockito.when(descriptor.getDefaultSuffix()).thenReturn("DOMAIN");
PowerMockito.mockStatic(Mailer.class);
PowerMockito.doReturn(descriptor).when(Mailer.class, "descriptor");
}Example 65
| Project: libdynticker-master File: GetPairsFromAPITest.java View source code |
@Test
public void testSecondGetPairsFromAPIDoesntActive() {
try {
// Exchange exchange = PowerMockito.spy(testExchange);
exchange.setExpiredPeriod(Long.MAX_VALUE);
exchange.getPairs();
verify(exchange, Mockito.times(1)).getPairsFromAPI();
Assert.assertNotNull(exchange.getTimestamp());
exchange.getPairs();
verify(exchange, Mockito.times(1)).getPairsFromAPI();
} catch (IOException e) {
e.printStackTrace();
Assert.fail();
}
}Example 66
| Project: liferay-portal-master File: DestinationStatisticsManagerTest.java View source code |
@Test
public void testRegisterMBean() throws Exception {
PowerMockito.when(_destination.getName()).thenReturn("test");
ObjectName objectName = new ObjectName("com.liferay.portal.messaging:classification=" + "messaging_destination,name=MessagingDestinationStatistics-" + _destination.getName());
_mBeanServer.registerMBean(new DestinationStatisticsManager(_destination), objectName);
Assert.assertTrue(_mBeanServer.isRegistered(objectName));
}Example 67
| Project: nic-master File: IntentNotificationSupplierImplTest.java View source code |
@Before
public void setup() {
/**
* Create required mock objects and define mocking functionality
* for mock objects.
*/
mockDataBroker = mock(DataBroker.class);
mockRegistryService = mock(EventRegistryService.class);
mockIntent = mock(Intent.class);
mockInstanceIdentifier = mock(InstanceIdentifier.class);
Bundle mockBundle = mock(Bundle.class);
BundleContext mockBundleContext = mock(BundleContext.class);
ServiceReference<EventRegistryService> mockServiceReference = mock(ServiceReference.class);
PowerMockito.mockStatic(FrameworkUtil.class);
when(FrameworkUtil.getBundle(IntentNotificationSupplierImpl.class)).thenReturn(mockBundle);
when(mockBundle.getBundleContext()).thenReturn(mockBundleContext);
when(mockBundleContext.getServiceReference(EventRegistryService.class)).thenReturn(mockServiceReference);
when(mockBundleContext.getService(mockServiceReference)).thenReturn(mockRegistryService);
mockIntentSupplier = new IntentNotificationSupplierImpl(mockDataBroker);
verify(mockRegistryService).setEventTypeService(mockIntentSupplier, EventType.INTENT_ADDED, EventType.INTENT_REMOVED, EventType.INTENT_UPDATE);
}Example 68
| Project: nodejs-plugin-master File: NodeJSInstallerTest.java View source code |
/**
* Verify that the installer skip install of global package also if
* npmPackage is an empty/spaces string.
* <p>
* This could happen because after migration 0.2 -> 1.0 the persistence
* could have npmPackages value empty or with spaces. XStream
* de-serialisation does use constructs object using constructor so value
* can be safely set to null.
*/
@Issue("JENKINS-41876")
@Test
public void test_skip_install_global_packages_when_empty() throws Exception {
String expectedPackages = " ";
int expectedRefreshHours = NodeJSInstaller.DEFAULT_NPM_PACKAGES_REFRESH_HOURS;
Node currentNode = mock(Node.class);
// mock all the static methods in the class
PowerMockito.mockStatic(NodeJSInstaller.class);
// create partial mock
NodeJSInstaller installer = new NodeJSInstaller("test-id", expectedPackages, expectedRefreshHours);
NodeJSInstaller spy = PowerMockito.spy(installer);
// use Mockito to set up your expectation
when(NodeJSInstaller.areNpmPackagesUpToDate(null, expectedPackages, expectedRefreshHours)).thenThrow(new AssertionError());
PowerMockito.suppress(PowerMockito.methodsDeclaredIn(DownloadFromUrlInstaller.class));
PowerMockito.doReturn(null).when(spy).getInstallable();
PowerMockito.doReturn(Platform.LINUX).when(spy, "getPlatform", currentNode);
PowerMockito.doReturn(CPU.amd64).when(spy, "getCPU", currentNode);
when(spy.getNpmPackages()).thenReturn(expectedPackages);
// execute test
spy.performInstallation(mock(ToolInstallation.class), currentNode, mock(TaskListener.class));
}Example 69
| Project: opentsdb-master File: TestFileSystem.java View source code |
@Before
public void setUp() throws Exception {
mockFile = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(mockFile);
PowerMockito.when(mockFile, "getParent").thenReturn("/temp/opentsdb");
PowerMockito.when(mockFile, "exists").thenReturn(true);
PowerMockito.when(mockFile, "isDirectory").thenReturn(true);
PowerMockito.when(mockFile, "canWrite").thenReturn(true);
}Example 70
| Project: osiris-master File: MapFileRepositoryCustoImplTest.java View source code |
@Test
public void getFileMapByAppId() throws Exception {
//Fixture
Mockito.when(mongoTemplate.getDb()).thenReturn(db);
PowerMockito.whenNew(GridFS.class).withArguments(db, collectionNameMap).thenReturn(gridFS);
Mockito.when(gridFS.findOne(idApp)).thenReturn(gridFSFile);
Mockito.when(gridFSFile.getInputStream()).thenReturn(inputStream);
// Experimentations
InputStream response = mapFileRepositoryCustomImpl.getMapFileByAppId(idApp);
// Expectations
Mockito.verify(gridFS).findOne(idApp);
Mockito.verify(gridFSFile).getInputStream();
Assert.assertEquals("File .map must be the same", inputStream, response);
}Example 71
| Project: ovsdb-master File: ServiceHelperTest.java View source code |
@Test
public /**
* Test method for
* {@link ServiceHelper#getGlobalInstance(Class, Object)}
*/
void getGlobalInstanceTest() {
Bundle bundle = new MockBundle();
PowerMockito.mockStatic(FrameworkUtil.class);
PowerMockito.when(FrameworkUtil.getBundle(any(Class.class))).thenReturn(null);
Object object = ServiceHelper.getGlobalInstance(Test.class, this);
assertNull("Service should be null", object);
PowerMockito.when(FrameworkUtil.getBundle(any(Class.class))).thenReturn(bundle);
object = ServiceHelper.getGlobalInstance(Test.class, this);
assertNotNull("Service should not be null", object);
}Example 72
| Project: powermock-master File: FinalEqualsClassTest.java View source code |
@Test
public void callingEqualsDoesntCauseStackOverflow() throws Exception {
FinalEqualsClass fc = new FinalEqualsClass();
fc.foo();
FinalEqualsClass mock = PowerMockito.mock(FinalEqualsClass.class);
FinalEqualsClass mock2 = PowerMockito.mock(FinalEqualsClass.class);
PowerMockito.when(mock.foo()).thenReturn("bar");
fc = PowerMockito.spy(fc);
PowerMockito.when(fc.foo()).thenReturn("bar");
fc.equals(mock);
assertEquals("bar", mock.foo());
assertEquals("bar", fc.foo());
assertEquals(mock, mock);
assertFalse(mock.equals(mock2));
}Example 73
| Project: ProcessPuzzleFramework-master File: RunTimeClassHierarchyAnalyserTest.java View source code |
@Before
public void beforeEachTest() {
currentUser = mock(User.class);
userRequestManager = mock(UserRequestManager.class);
PowerMockito.mockStatic(UserRequestManager.class);
when(UserRequestManager.getInstance()).thenReturn(userRequestManager);
when(userRequestManager.currentUser()).thenReturn(currentUser);
UserRequestManager.getInstance().currentUser();
hierarchyAnalyser = new RunTimeClassHierarchyAnalyser();
}Example 74
| Project: ScoreboardStats-master File: ReplaceManagerTest.java View source code |
@Test
public void testUnregister() throws Exception {
PowerMockito.mockStatic(Bukkit.class);
Mockito.when(Bukkit.getPluginManager()).thenReturn(PowerMockito.mock(SimplePluginManager.class));
Mockito.when(Bukkit.getMessenger()).thenReturn(PowerMockito.mock(StandardMessenger.class));
Mockito.when(Bukkit.getScheduler()).thenReturn(PowerMockito.mock(BukkitScheduler.class));
ScoreboardStats plugin = PowerMockito.mock(ScoreboardStats.class);
PowerMockito.when(plugin.getLogger()).thenReturn(Logger.getGlobal());
ReplaceManager replaceManager = new ReplaceManager(null, plugin);
testLegacy(replaceManager);
testAbstract(plugin, replaceManager);
}Example 75
| Project: spring-mvc-qq-weibo-master File: WebDriverFactoryTest.java View source code |
@Test
public void buildWebDriver() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.whenNew(FirefoxDriver.class).withNoArguments().thenReturn(firefoxDriver);
WebDriver driver = WebDriverFactory.createDriver("firefox");
assertThat(driver).isInstanceOf(FirefoxDriver.class);
PowerMockito.whenNew(InternetExplorerDriver.class).withNoArguments().thenReturn(internetExplorerDriver);
driver = WebDriverFactory.createDriver("ie");
assertThat(driver).isInstanceOf(InternetExplorerDriver.class);
PowerMockito.whenNew(ChromeDriver.class).withNoArguments().thenReturn(chromerDriver);
driver = WebDriverFactory.createDriver("chrome");
assertThat(driver).isInstanceOf(ChromeDriver.class);
PowerMockito.whenNew(RemoteWebDriver.class).withArguments(new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.firefox()).thenReturn(remoteWebDriver);
driver = WebDriverFactory.createDriver("remote:localhost:4444:firefox");
assertThat(driver).isInstanceOf(RemoteWebDriver.class);
}Example 76
| Project: stackify-api-java-master File: LogSenderTest.java View source code |
/**
* testSend
* @throws Exception
*/
@Test
public void testSend() throws Exception {
ObjectMapper objectMapper = Mockito.mock(ObjectMapper.class);
Mockito.when(objectMapper.writer()).thenReturn(Mockito.mock(ObjectWriter.class));
ApiConfiguration apiConfig = ApiConfiguration.newBuilder().apiUrl("url").apiKey("key").build();
LogSender sender = new LogSender(apiConfig, objectMapper);
HttpClient httpClient = PowerMockito.mock(HttpClient.class);
PowerMockito.whenNew(HttpClient.class).withAnyArguments().thenReturn(httpClient);
PowerMockito.when(httpClient.post(Mockito.anyString(), (byte[]) Mockito.any())).thenReturn("");
sender.send(Mockito.mock(LogMsgGroup.class));
}Example 77
| Project: stokesdrift-master File: DriftRackApplicationFactoryTest.java View source code |
@Test
public void testLoadPaths() throws Exception {
DriftRackApplicationFactory factory = new DriftRackApplicationFactory();
ServletContext servletContext = PowerMockito.mock(ServletContext.class);
ServletRackConfig config = new ServletRackConfig(servletContext);
ServletRackContext context = new DefaultServletRackContext(config);
// Shouldn't add since the gems direction doesn't exist
URL configRuFile = this.getClass().getClassLoader().getResource("examples/config.ru");
File file = new File(configRuFile.toURI());
String jrubyHome = file.getParent();
URI libUri = Ruby.class.getProtectionDomain().getCodeSource().getLocation().toURI();
File libDirectory = new File(libUri);
System.setProperty("STOKESDRIFT_LIB_DIR", libDirectory.getParent());
System.setProperty("JRUBY_HOME", jrubyHome);
System.setProperty("GEM_PATH", "test/home/gem_path");
factory.init(context);
Ruby runtime = factory.newRuntime();
Assert.assertNotNull(runtime);
RubyInstanceConfig rackConfig = factory.getRuntimeConfig();
List<String> loadPaths = rackConfig.getLoadPaths();
Assert.assertTrue(loadPaths.size() > 0);
Assert.assertTrue(loadPaths.contains("test/home/gem_path"));
Assert.assertEquals(jrubyHome, rackConfig.getJRubyHome());
configRuFile = this.getClass().getClassLoader().getResource("examples/test_paths.rb");
byte[] scriptBytes = Files.readAllBytes(Paths.get(configRuFile.toURI()));
IRubyObject rubyObject = runtime.executeScript(new String(scriptBytes), "test_paths.rb");
Assert.assertEquals("horray", rubyObject.asString().toString());
}Example 78
| Project: sxp-master File: SxpControllerModuleTest.java View source code |
@Before
public void init() {
PowerMockito.mockStatic(DatastoreAccess.class);
datastoreAccess = mock(DatastoreAccess.class);
dependencyResolver = mock(DependencyResolver.class);
moduleIdentifier = mock(ModuleIdentifier.class);
PowerMockito.when(DatastoreAccess.getInstance(any(DataBroker.class))).thenReturn(datastoreAccess);
SxpControllerModule.notifyBundleActivated();
}Example 79
| Project: tachyon-master File: LineageFileOutStreamTest.java View source code |
@Test
public void persistHandledByMaster() throws Exception {
FileSystemContext context = PowerMockito.mock(FileSystemContext.class);
FileSystemMasterClient client = PowerMockito.mock(FileSystemMasterClient.class);
Mockito.when(context.acquireMasterClientResource()).thenReturn(new DummyCloseableResource<>(client));
LineageFileOutStream stream = new LineageFileOutStream(context, new AlluxioURI("/path"), OutStreamOptions.defaults().setWriteType(WriteType.ASYNC_THROUGH));
stream.close();
// The lineage file out stream doesn't manage asynchronous persistence.
Mockito.verify(client, Mockito.times(0)).scheduleAsyncPersist(new AlluxioURI("/path"));
}Example 80
| Project: tdq-studio-se-master File: ExportWizardPageTest.java View source code |
/**
* Test method for {@link org.talend.dataprofiler.core.ui.imex.ExportWizardPage#updateBasePath()}.
*/
@Test
public void testUpdateBasePath() {
// mock mockExportWizardPage.isDirState()
//$NON-NLS-1$
String return1 = "dirTxt";
//$NON-NLS-1$
String return2 = "archTxt";
ExportWizardPage exportWizardPage = new ExportWizardPage(null);
ExportWizardPage mockExportWizardPage = Mockito.spy(exportWizardPage);
// Shell shell = new Shell();
// mockExportWizardPage.createSelectComposite(shell);
// mockExportWizardPage.createRepositoryTree(shell);
PowerMockito.doReturn(true).when(mockExportWizardPage).isDirState();
PowerMockito.doReturn(return1).when(mockExportWizardPage).getTextContent((Text) Mockito.any());
PowerMockito.doNothing().when(mockExportWizardPage).textModified(Mockito.anyString());
String updateBasePath1 = mockExportWizardPage.updateBasePath();
PowerMockito.doReturn(false).when(mockExportWizardPage).isDirState();
PowerMockito.doReturn(return2).when(mockExportWizardPage).getTextContent((Text) Mockito.any());
String updateBasePath2 = mockExportWizardPage.updateBasePath();
Mockito.verify(mockExportWizardPage, Mockito.times(2)).isDirState();
Mockito.verify(mockExportWizardPage, Mockito.times(2)).getTextContent((Text) Mockito.any());
Mockito.verify(mockExportWizardPage, Mockito.times(2)).textModified(Mockito.anyString());
// Mockito.verify(mockExportWizardPage).createSelectComposite(shell);
// Mockito.verify(mockExportWizardPage).createRepositoryTree(shell);
assertEquals(updateBasePath1, return1);
assertEquals(updateBasePath2, return2);
// shell.dispose();
}Example 81
| Project: transfuse-master File: CodeGenerationScopedTransactionWorkerTest.java View source code |
@Before
public void setUp() throws Exception {
mockCodeModel = PowerMockito.mock(JCodeModel.class);
mockCodeWriter = PowerMockito.mock(CodeWriter.class);
mockResourceWriter = PowerMockito.mock(CodeWriter.class);
mockWorker = PowerMockito.mock(TransactionWorker.class);
worker = new CodeGenerationScopedTransactionWorker<Object, Object>(mockCodeModel, mockCodeWriter, mockResourceWriter, mockWorker);
}Example 82
| Project: tsdr-master File: ActivatorTest.java View source code |
@Test
public void destroy() throws Exception {
Activator activator = new Activator();
Service service = Mockito.mock(Service.class);
Mockito.doNothing().when(service).awaitTerminated(any(Long.class), any(TimeUnit.class));
PowerMockito.doReturn(service).when((AbstractScheduledService) store).stopAsync();
activator.setStore(store);
activator.destroy(null, null);
}Example 83
| Project: twice-master File: AuthenticationTest.java View source code |
@Test
public void testGetUserName() {
// given
PowerMockito.mockStatic(GWT.class);
PowerMockito.mockStatic(Window.class);
when(Window.prompt(anyString(), anyString())).thenReturn("myUserName");
// when
String userName = Authentication.getUserName();
// mock another return value - the username should stay the same, because prompt is not invoked anymore
when(Window.prompt(anyString(), anyString())).thenReturn("anotherUserName");
String userNameAfterSecondRequest = Authentication.getUserName();
// then
Assert.assertNotNull(userName);
Assert.assertEquals("myUserName", userName);
Assert.assertNotNull(userNameAfterSecondRequest);
Assert.assertEquals("myUserName", userNameAfterSecondRequest);
}Example 84
| Project: Weasis-master File: ModelListHelper.java View source code |
protected ImageElement mockImage(String seriesUuid, String uuid) {
ImageElement img = PowerMockito.mock(ImageElement.class);
if (Objects.isNull(uuid) && Objects.isNull(seriesUuid)) {
PowerMockito.when(img.getTagValue(Mockito.any())).thenReturn(null);
} else if (Objects.nonNull(uuid) && Objects.isNull(seriesUuid)) {
PowerMockito.when(img.getTagValue(Mockito.any())).thenReturn(uuid, null, uuid);
} else {
PowerMockito.when(img.getTagValue(Mockito.any())).thenReturn(uuid, seriesUuid);
}
MediaReader mediaReader = PowerMockito.mock(MediaReader.class);
PowerMockito.when(img.getMediaReader()).thenReturn(mediaReader);
PowerMockito.when(mediaReader.getMediaElementNumber()).thenReturn(1);
PowerMockito.when(img.getKey()).thenReturn(0);
return img;
}Example 85
| Project: WhatsApp-Web-master File: AccessTokenCacheTest.java View source code |
@Before
public void before() throws Exception {
mockStatic(FacebookSdk.class);
sharedPreferences = Robolectric.application.getSharedPreferences(AccessTokenManager.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
sharedPreferences.edit().clear().commit();
cachingStrategyFactory = mock(AccessTokenCache.SharedPreferencesTokenCachingStrategyFactory.class);
when(cachingStrategyFactory.create()).thenReturn(cachingStrategy);
stub(PowerMockito.method(Utility.class, "awaitGetGraphMeRequestWithCache")).toReturn(new JSONObject().put("id", "1000"));
}Example 86
| Project: active-directory-plugin-master File: RemoveIrrelevantGroupsTest.java View source code |
/**
* Makes Jenkins.getInstance().getAuthorizationStrategy.getGroups()
* return argument groups.
*/
private void setUpJenkinsUsedGroups(String... groups) {
Set<String> usedGroups = new HashSet<String>();
for (String group : groups) {
usedGroups.add(group);
}
AuthorizationStrategy authorizationStrategy = PowerMockito.mock(AuthorizationStrategy.class);
when(authorizationStrategy.getGroups()).thenReturn(usedGroups);
jenkinsRule.getInstance().setAuthorizationStrategy(authorizationStrategy);
}Example 87
| Project: blueflood-master File: BluefloodServiceStarterTest.java View source code |
@Before
public void setUp() throws Exception {
Configuration config = Configuration.getInstance();
config.init();
config.setProperty(CoreConfig.ZOOKEEPER_CLUSTER, "NONE");
config.setProperty(CoreConfig.INGEST_MODE, "false");
config.setProperty(CoreConfig.ROLLUP_MODE, "false");
config.setProperty(CoreConfig.QUERY_MODE, "false");
PowerMockito.spy(BluefloodServiceStarter.class);
PowerMockito.doReturn(mock(MetricRegistry.class)).when(BluefloodServiceStarter.class, "getRegistry");
}Example 88
| Project: datacollector-master File: TestHttpProcessor.java View source code |
@Override
public List<Stage.ConfigIssue> runStageValidation(String url) throws Exception {
HttpProcessorConfig config = getConf("http://localhost:10000");
config.client.useProxy = true;
config.client.proxy.uri = url;
HttpProcessor processor = PowerMockito.spy(new HttpProcessor(config));
ProcessorRunner runner = new ProcessorRunner.Builder(HttpDProcessor.class, processor).addOutputLane("lane").setOnRecordError(OnRecordError.TO_ERROR).build();
return runner.runValidateConfigs();
}Example 89
| Project: openmrs-contrib-android-client-master File: ACUnitTestBase.java View source code |
protected void mockActiveAndroidContext() {
PowerMockito.mockStatic(Cache.class);
PowerMockito.mockStatic(ContentProvider.class);
TableInfo tableInfo = PowerMockito.mock(TableInfo.class);
Context context = PowerMockito.mock(Context.class);
ContentResolver resolver = PowerMockito.mock(ContentResolver.class);
SQLiteDatabase sqliteDb = PowerMockito.mock(SQLiteDatabase.class);
ContentValues vals = PowerMockito.mock(ContentValues.class);
try {
PowerMockito.whenNew(ContentValues.class).withNoArguments().thenReturn(vals);
} catch (Exception e) {
e.printStackTrace();
}
when(Cache.openDatabase()).thenReturn(sqliteDb);
when(context.getContentResolver()).thenReturn(resolver);
doNothing().when(resolver).notifyChange(any(Uri.class), any(ContentObserver.class));
when(tableInfo.getFields()).thenReturn(new ArrayList<>());
when(tableInfo.getTableName()).thenReturn("TestTable");
when(Cache.getTableInfo(any(Class.class))).thenReturn(tableInfo);
when(Cache.getContext()).thenReturn(context);
when(ContentProvider.createUri(anyObject(), anyLong())).thenReturn(null);
}Example 90
| Project: RxBonjour-master File: SupportBonjourBroadcastTest.java View source code |
@Test
public void testAddAndRemoveOneCycle() throws Exception {
BonjourBroadcastBuilder builder = PowerMockito.spy(SupportBonjourBroadcast.newBuilder("_http._tcp"));
BonjourBroadcast<?> broadcast = builder.build();
TestSubscriber<BonjourEvent> subscriber = new TestSubscriber<>();
ArgumentCaptor<ServiceInfo> captor = ArgumentCaptor.forClass(ServiceInfo.class);
broadcast.start(context).subscribe(subscriber);
subscriber.assertNoErrors();
verify(jmdns, times(1)).registerService(captor.capture());
ServiceInfo serviceInfo = captor.getValue();
assertEquals(serviceInfo.getType(), "_http._tcp.local.");
subscriber.unsubscribe();
verify(jmdns, times(1)).unregisterService(serviceInfo);
verify(jmdns, times(1)).close();
setJmDNSMockClosed();
}Example 91
| Project: stratosphere-master File: InstanceProfilerTest.java View source code |
@Before
public void setUp() throws Exception {
initMocks(this);
when(this.infoMock.address()).thenReturn(this.addressMock);
when(this.addressMock.getHostAddress()).thenReturn("192.168.1.1");
whenNew(FileReader.class).withArguments(InstanceProfiler.PROC_STAT).thenReturn(this.cpuReaderMock);
whenNew(BufferedReader.class).withArguments(this.cpuReaderMock).thenReturn(this.cpuBufferMock);
when(this.cpuBufferMock.readLine()).thenReturn("cpu 222875 20767 209704 3782096 209864 0 1066 0 0 0");
whenNew(FileReader.class).withArguments(InstanceProfiler.PROC_NET_DEV).thenReturn(this.networkReaderMock);
whenNew(BufferedReader.class).withArguments(this.networkReaderMock).thenReturn(this.networkBufferMock);
when(this.networkBufferMock.readLine()).thenReturn(" eth0: 364729203 286442 0 0 0 0 0 1060 14483806 191563 0 0 0 0 0 0", (String) null, " eth0: 364729203 286442 0 0 0 0 0 1060 14483806 191563 0 0 0 0 0 0", (String) null, " eth0: 364729203 286442 0 0 0 0 0 1060 14483806 191563 0 0 0 0 0 0", (String) null);
whenNew(FileReader.class).withArguments(InstanceProfiler.PROC_MEMINFO).thenReturn(this.memoryReaderMock);
whenNew(BufferedReader.class).withArguments(this.memoryReaderMock).thenReturn(this.memoryBufferMock);
when(this.memoryBufferMock.readLine()).thenReturn("MemTotal: 8052956 kB", "MemFree: 3999880 kB", "Buffers: 77216 kB", "Cached: 1929640 kB", null, "MemTotal: 8052956 kB", "MemFree: 3999880 kB", "Buffers: 77216 kB", "Cached: 1929640 kB", null, "MemTotal: 8052956 kB", "MemFree: 3999880 kB", "Buffers: 77216 kB", "Cached: 1929640 kB", null);
PowerMockito.mockStatic(System.class);
when(System.currentTimeMillis()).thenReturn(0L);
this.out = new InstanceProfiler(this.infoMock);
}Example 92
| Project: stratosphere-OLD-REPO-master File: InstanceProfilerTest.java View source code |
@Before
public void setUp() throws Exception {
initMocks(this);
when(this.infoMock.getAddress()).thenReturn(this.addressMock);
when(this.addressMock.getHostAddress()).thenReturn("192.168.1.1");
whenNew(FileReader.class).withArguments(InstanceProfiler.PROC_STAT).thenReturn(this.cpuReaderMock);
whenNew(BufferedReader.class).withArguments(this.cpuReaderMock).thenReturn(this.cpuBufferMock);
when(this.cpuBufferMock.readLine()).thenReturn("cpu 222875 20767 209704 3782096 209864 0 1066 0 0 0");
whenNew(FileReader.class).withArguments(InstanceProfiler.PROC_NET_DEV).thenReturn(this.networkReaderMock);
whenNew(BufferedReader.class).withArguments(this.networkReaderMock).thenReturn(this.networkBufferMock);
when(this.networkBufferMock.readLine()).thenReturn(" eth0: 364729203 286442 0 0 0 0 0 1060 14483806 191563 0 0 0 0 0 0", (String) null, " eth0: 364729203 286442 0 0 0 0 0 1060 14483806 191563 0 0 0 0 0 0", (String) null, " eth0: 364729203 286442 0 0 0 0 0 1060 14483806 191563 0 0 0 0 0 0", (String) null);
whenNew(FileReader.class).withArguments(InstanceProfiler.PROC_MEMINFO).thenReturn(this.memoryReaderMock);
whenNew(BufferedReader.class).withArguments(this.memoryReaderMock).thenReturn(this.memoryBufferMock);
when(this.memoryBufferMock.readLine()).thenReturn("MemTotal: 8052956 kB", "MemFree: 3999880 kB", "Buffers: 77216 kB", "Cached: 1929640 kB", null, "MemTotal: 8052956 kB", "MemFree: 3999880 kB", "Buffers: 77216 kB", "Cached: 1929640 kB", null, "MemTotal: 8052956 kB", "MemFree: 3999880 kB", "Buffers: 77216 kB", "Cached: 1929640 kB", null);
PowerMockito.mockStatic(System.class);
when(System.currentTimeMillis()).thenReturn(0L);
this.out = new InstanceProfiler(this.infoMock);
}Example 93
| Project: uberfire-master File: DisposableShutdownServiceTest.java View source code |
@Test
public void testGeneralStatic() {
mockStatic(PriorityDisposableRegistry.class);
mockStatic(SimpleAsyncExecutorService.class);
mockStatic(FileSystemProviders.class);
final JGitFileSystemProvider disposableProvider = mock(JGitFileSystemProvider.class);
when(FileSystemProviders.installedProviders()).thenReturn(Arrays.asList(mock(FileSystemProvider.class), disposableProvider));
new DisposableShutdownService().contextDestroyed(null);
verify(disposableProvider, times(1)).dispose();
PowerMockito.verifyStatic();
SimpleAsyncExecutorService.shutdownInstances();
PowerMockito.verifyStatic();
PriorityDisposableRegistry.clear();
}Example 94
| Project: APP-dashboard-master File: SessionCheckInterceptorTest.java View source code |
@Test
public void testPreHandle() throws Exception {
SessionCheckInterceptor scInterceptor = new SessionCheckInterceptor();
PowerMockito.mockStatic(SecurityUtil.class);
PowerMockito.when(SecurityUtil.getToken()).thenReturn("sravan");
MockHttpServletRequest request = new MockHttpServletRequest() {
public HttpSession getSession() {
return new MockHttpSession();
}
public Cookie[] getCookies() {
Cookie c = new Cookie(SLIAuthenticationEntryPoint.DASHBOARD_COOKIE, "fake");
return new Cookie[] { c };
}
public String getRequestURI() {
return "fake_uri";
}
};
MockHttpServletResponse response = new MockHttpServletResponse() {
public void sendRedirect(String url) {
assertEquals(url, "fake_uri");
}
};
RESTClient restClient = new RESTClient() {
public JsonObject sessionCheck(String token) {
JsonObject json = new JsonObject();
json.addProperty("authenticated", false);
return json;
}
};
scInterceptor.setRestClient(restClient);
assertEquals(scInterceptor.preHandle(request, response, null), false);
}Example 95
| Project: catch-exception-master File: ExceptionProcessingInterceptorTest.java View source code |
/**
* Checks fix for: when using catch-exception and spring proxy on same
* class, both framework tries to generate same class name and the latter
* one fails.
*
* @throws Throwable
*/
@Test
@PrepareForTest(Method.class)
public void intercept_useMockitoNamingPolicy() throws Throwable {
TestClazz testObject = new TestClazz();
Method method = PowerMockito.mock(Method.class);
Object[] args = new Object[0];
MethodProxy methodProxy = MethodProxy.create(TestClazz.class, Void.class, "()V", "methodToBeProxy", "methodToBeProxy");
ExceptionProcessingInterceptor<Exception> instance = new ExceptionProcessingInterceptor<Exception>(testObject, Exception.class, false);
instance.intercept(testObject, method, args, methodProxy);
Object currentNamingPolicy = getCurrentNamingPolicy(methodProxy);
Assert.assertSame("namingPolicy", currentNamingPolicy, MockitoNamingPolicy.INSTANCE);
}Example 96
| Project: cloudstack-master File: CitrixResourceBaseTest.java View source code |
public void testGetPathFilesListReturned() {
String patch = citrixResourceBase.getPatchFilePath();
PowerMockito.mockStatic(Script.class);
Mockito.when(Script.findScript("", patch)).thenReturn(patch);
File expected = new File(patch);
String pathExpected = expected.getAbsolutePath();
List<File> files = citrixResourceBase.getPatchFiles();
String receivedPath = files.get(0).getAbsolutePath();
Assert.assertEquals(receivedPath, pathExpected);
}Example 97
| Project: clt-master File: ContentScriptEventHandlerTest.java View source code |
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(SelectionProvider.class);
PowerMockito.when(SelectionProvider.getSelection()).thenReturn("word");
PowerMockito.suppress(event.getClass().getMethod("equals", Object.class));
PowerMockito.doReturn("mouseup").when(event).getType();
PowerMockito.doReturn(true).when(event).getCtrlKey();
PowerMockito.doReturn(true).when(event).getAltKey();
}Example 98
| Project: commons-compress-master File: SevenZNativeHeapTest.java View source code |
@Test
public void testEndDeflaterOnCloseStream() throws Exception {
final Deflater deflater = PowerMockito.spy(new Deflater());
PowerMockito.whenNew(Deflater.class).withAnyArguments().thenReturn(deflater);
final OutputStream outputStream = deflateDecoder.encode(new ByteArrayOutputStream(), 9);
outputStream.close();
Mockito.verify(deflater).end();
}Example 99
| Project: Consent2Share-master File: AuditServiceImplStaticTest.java View source code |
@Test
public void testInit() throws AuditException {
// Arrange
PowerMockito.mockStatic(AuditorFactory.class);
PowerMockito.doNothing().when(AuditorFactory.class);
AuditorFactory.setApplicationName(anyString());
// Act
sut.init();
// Assert
PowerMockito.verifyStatic(times(1));
AuditorFactory.setApplicationName(anyString());
}Example 100
| Project: DataX-master File: StandAloneSchedulerTest.java View source code |
@Test
public void testSchedule() throws NoSuchFieldException, IllegalAccessException {
int taskNumber = 10;
List<Configuration> jobList = new ArrayList<Configuration>();
List<Configuration> internal = new ArrayList<Configuration>();
int randomSize = 20;
int length = RandomUtils.nextInt(0, randomSize) + 1;
for (int i = 0; i < length; i++) {
internal.add(Configuration.newDefault());
}
LocalTGCommunicationManager.clear();
for (int i = 0; i < taskNumber; i++) {
Configuration configuration = Configuration.newDefault();
configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_REPORTINTERVAL, 11);
configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, 0);
configuration.set(CoreConstant.DATAX_JOB_CONTENT, internal);
configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_MODE, ExecuteMode.STANDALONE.getValue());
configuration.set(CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_ID, i);
jobList.add(configuration);
LocalTGCommunicationManager.registerTaskGroupCommunication(i, new Communication());
}
StandAloneJobContainerCommunicator standAloneJobContainerCommunicator = PowerMockito.mock(StandAloneJobContainerCommunicator.class);
ProcessInnerScheduler scheduler = PowerMockito.spy(new StandAloneScheduler(standAloneJobContainerCommunicator));
PowerMockito.doNothing().when(scheduler).startAllTaskGroup(anyListOf(Configuration.class));
Communication communication = new Communication();
communication.setState(State.SUCCEEDED);
PowerMockito.when(standAloneJobContainerCommunicator.collect()).thenReturn(communication);
PowerMockito.doNothing().when(standAloneJobContainerCommunicator).report(communication);
scheduler.schedule(jobList);
}Example 101
| Project: Decision-master File: ClusterBarrierManagerTest.java View source code |
@Test
public void testManageAckBarrierShouldBeOk() throws Exception {
Integer ackTimeout = 500;
String barrierPath = "/stratio/decision/barrier";
Integer nodesExpected = 2;
ClusterSyncManager clusterSyncManager = mock(ClusterSyncManager.class);
when(clusterSyncManager.getClient()).thenReturn(curatorFramework);
final ClusterBarrierManager clusterBarrierManager = PowerMockito.spy(new ClusterBarrierManager(clusterSyncManager, ackTimeout));
barrier = mock(DistributedDoubleBarrier.class);
when(barrier.enter(anyLong(), any(TimeUnit.class))).thenReturn(true);
PowerMockito.doReturn(barrier).when(clusterBarrierManager).getDistributedDoubleBarrier(anyString(), anyInt());
assertEquals(true, clusterBarrierManager.manageAckBarrier(barrierPath, nodesExpected));
}