Java Code Examples for org.powermock.api.easymock.PowerMock#mockStaticPartial()

The following examples show how to use org.powermock.api.easymock.PowerMock#mockStaticPartial() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QueryMetricsEnrichmentInterceptorTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostProcess_BaseQueryResponse() throws Exception {
    QueryMetricsEnrichmentInterceptor subject = new QueryMetricsEnrichmentInterceptor();
    
    // Set expectations
    expect(responseContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.keySet()).andReturn(new HashSet<>());
    expect(responseContext.getStatus()).andReturn(HttpResponseCodes.SC_OK);
    expect(responseContext.getJaxrsResponse()).andReturn(jaxrsResponse);
    expect(jaxrsResponse.getAnnotations()).andReturn(new Annotation[] {enrichQueryMetrics});
    PowerMock.mockStaticPartial(FindAnnotation.class, "findAnnotation");
    expect(FindAnnotation.findAnnotation(isA(Annotation[].class), eq(EnrichQueryMetrics.class))).andReturn(this.enrichQueryMetrics);
    expect(responseContext.getEntity()).andReturn(baseQueryResponse);
    expect(enrichQueryMetrics.methodType()).andReturn(EnrichQueryMetrics.MethodType.CREATE);
    expect(baseQueryResponse.getQueryId()).andReturn(UUID.randomUUID().toString());
    requestContext.setProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")), anyObject());
    requestContext.setProperty(eq(QueryCall.class.getName()), isA(QueryCall.class));
    
    // Run the test
    PowerMock.replayAll();
    subject.filter(requestContext, responseContext);
    PowerMock.verifyAll();
}
 
Example 2
Source File: IntellijMocker.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Mocks static <code>getInstance()</code> calls.
 *
 * <p>If you use this utility, make sure to (1) run your test class with {@link PowerMockRunner}
 * and (2) add the class to be mocked to the "prepare for test" list:
 *
 * <p>
 *
 * <pre>
 * {@literal @}RunWith(PowerMockRunner.class)
 * {@literal @}PrepareForTest({ IntellijClassToMock.class })
 * public class MyTestClass {
 *     // ...
 * }
 * </pre>
 *
 * @param clazz Class to mock
 * @param argClass class of the argument that is passed to <code>getInstance()</code>, if any. Can
 *     be <code>null</code>
 */
public static <T> void mockStaticGetInstance(Class<T> clazz, Class<?> argClass) {
  String method = "getInstance";

  T instance = createNiceMock(clazz);
  EasyMock.replay(instance);

  PowerMock.mockStaticPartial(clazz, method);
  try {
    if (argClass == null) {
      // method has no arguments
      clazz.getMethod(method).invoke(null);
    } else {
      // method has one argument
      clazz.getMethod(method, argClass).invoke(null, anyObject(argClass));
    }
  } catch (Exception e) {
    e.printStackTrace();
    Assert.fail("reflection error, see stacktrace");
  }

  expectLastCall().andStubReturn(instance);
  PowerMock.replay(clazz);
}
 
Example 3
Source File: NGramTokenizationStrategyTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Test
public void testTokenize_LowMemory() throws Exception {
    // Create test input
    final NormalizedContentInterface nci = new NormalizedFieldAndValue("TEST", "test");
    
    // Calculate the expected number of n-grams
    final String fieldValue = nci.getIndexedFieldValue();
    int expectedNGramCount = BloomFilterUtil.predictNGramCount(fieldValue, MemoryStarvationStrategy.DEFAULT_MAX_NGRAM_LENGTH);
    
    // Set expectations
    PowerMock.mockStaticPartial(Logger.class, "getLogger");
    expect(Logger.getLogger(isA(Class.class))).andReturn(this.logger).anyTimes();
    PowerMock.mockStaticPartial(ResourceAvailabilityUtil.class, "isMemoryAvailable");
    expect(ResourceAvailabilityUtil.isMemoryAvailable(.05f)).andReturn(true);
    PowerMock.mockStaticPartial(ResourceAvailabilityUtil.class, "isMemoryAvailable");
    expect(ResourceAvailabilityUtil.isMemoryAvailable(.05f)).andReturn(false);
    this.logger.warn(isA(String.class), isA(LowMemoryException.class));
    
    // Run the test
    PowerMock.replayAll();
    MemoryStarvationStrategy subject = new MemoryStarvationStrategy(this.filter, .05f);
    NGramTokenizationStrategy strategy = new NGramTokenizationStrategy(subject);
    
    int result1 = strategy.tokenize(nci, MemoryStarvationStrategy.DEFAULT_MAX_NGRAM_LENGTH);
    PowerMock.verifyAll();
    
    // Verify results
    assertEquals("Strategy should have logged a low memory exception but still tokenized n-grams", expectedNGramCount, result1);
}
 
Example 4
Source File: NGramTokenizationStrategyTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Test
public void testTokenize_LowDiskSpace() throws Exception {
    // Create test input
    final NormalizedContentInterface nci = new NormalizedFieldAndValue("TEST", "test");
    
    // Calculate the expected number of n-grams
    final String fieldValue = nci.getIndexedFieldValue();
    int expectedNGramCount = BloomFilterUtil.predictNGramCount(fieldValue, DiskSpaceStarvationStrategy.DEFAULT_MAX_NGRAM_LENGTH);
    
    // Set expectations
    PowerMock.mockStaticPartial(Logger.class, "getLogger");
    expect(Logger.getLogger(isA(Class.class))).andReturn(this.logger).anyTimes();
    PowerMock.mockStaticPartial(ResourceAvailabilityUtil.class, "isDiskAvailable");
    expect(ResourceAvailabilityUtil.isDiskAvailable("/", .05f)).andReturn(true);
    PowerMock.mockStaticPartial(ResourceAvailabilityUtil.class, "isDiskAvailable");
    expect(ResourceAvailabilityUtil.isDiskAvailable("/", .05f)).andReturn(false);
    this.logger.warn(isA(String.class), isA(LowDiskSpaceException.class));
    
    // Run the test
    PowerMock.replayAll();
    DiskSpaceStarvationStrategy subject = new DiskSpaceStarvationStrategy(this.filter, .05f, "/");
    NGramTokenizationStrategy strategy = new NGramTokenizationStrategy(subject);
    int result1 = strategy.tokenize(nci, DiskSpaceStarvationStrategy.DEFAULT_MAX_NGRAM_LENGTH);
    PowerMock.verifyAll();
    
    // Verify results
    assertEquals("Strategy should have logged a low disk exception but still tokenized n-grams", expectedNGramCount, result1);
}
 
Example 5
Source File: AbstractContextTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setup() {
  container = ContextMocker.emptyContext();

  // mock IntelliJ dependencies
  mockStaticGetInstance(PropertiesComponent.class, null);

  // mock IntelliJ dependent calls to get current IDE and plugin version
  PowerMock.mockStaticPartial(
      IntellijVersionProvider.class, "getPluginVersion", "getBuildNumber");

  EasyMock.expect(IntellijVersionProvider.getPluginVersion()).andReturn("0.1.0");
  EasyMock.expect(IntellijVersionProvider.getBuildNumber()).andReturn("1");

  PowerMock.replay(IntellijVersionProvider.class);

  // mock application related requests
  MessageBusConnection messageBusConnection = EasyMock.createNiceMock(MessageBusConnection.class);
  EasyMock.replay(messageBusConnection);

  MessageBus messageBus = EasyMock.createNiceMock(MessageBus.class);
  EasyMock.expect(messageBus.connect()).andReturn(messageBusConnection);
  EasyMock.replay(messageBus);

  Application application = EasyMock.createNiceMock(Application.class);
  EasyMock.expect(application.getMessageBus()).andReturn(messageBus);
  EasyMock.replay(application);

  PowerMock.mockStaticPartial(ApplicationManager.class, "getApplication");
  EasyMock.expect(ApplicationManager.getApplication()).andReturn(application);
  PowerMock.replay(ApplicationManager.class);
}
 
Example 6
Source File: SarosSessionTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private static IWorkspace createWorkspaceMock(final List<Object> workspaceListeners) {

    final IWorkspace workspace = createMock(IWorkspace.class);

    workspace.addResourceChangeListener(isA(IResourceChangeListener.class), anyInt());

    expectLastCall()
        .andStubAnswer(
            new IAnswer<Object>() {

              @Override
              public Object answer() throws Throwable {
                workspaceListeners.add(getCurrentArguments()[0]);
                return null;
              }
            });

    workspace.removeResourceChangeListener(isA(IResourceChangeListener.class));

    expectLastCall()
        .andStubAnswer(
            new IAnswer<Object>() {

              @Override
              public Object answer() throws Throwable {
                workspaceListeners.remove(getCurrentArguments()[0]);
                return null;
              }
            });

    replay(workspace);

    PowerMock.mockStaticPartial(ResourcesPlugin.class, "getWorkspace");
    ResourcesPlugin.getWorkspace();
    expectLastCall().andReturn(workspace).anyTimes();
    PowerMock.replay(ResourcesPlugin.class);

    return workspace;
  }
 
Example 7
Source File: EclipseMocker.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/** Mock the static call {@link ResourcesPlugin#getWorkspace()}. */
public static void mockResourcesPlugin() {
  IWorkspaceRoot workspaceRoot = EasyMock.createNiceMock(IWorkspaceRoot.class);
  EasyMock.replay(workspaceRoot);

  final IWorkspace workspace = EasyMock.createNiceMock(IWorkspace.class);
  EasyMock.expect(workspace.getRoot()).andStubReturn(workspaceRoot);
  EasyMock.replay(workspace);

  PowerMock.mockStaticPartial(ResourcesPlugin.class, "getWorkspace");
  ResourcesPlugin.getWorkspace();
  EasyMock.expectLastCall().andReturn(workspace).anyTimes();
  PowerMock.replay(ResourcesPlugin.class);
}
 
Example 8
Source File: EclipseMocker.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/** Mock the static call {@link Platform#getBundle(String)}. */
public static void mockPlatform() {
  Bundle bundle = EasyMock.createNiceMock(Bundle.class);
  EasyMock.expect(bundle.getVersion()).andStubReturn(new Version("1.0.0.dummy"));
  EasyMock.replay(bundle);

  PowerMock.mockStaticPartial(Platform.class, "getBundle");
  Platform.getBundle("org.eclipse.core.runtime");
  EasyMock.expectLastCall().andStubReturn(bundle);
  PowerMock.replay(Platform.class);
}
 
Example 9
Source File: QueryMetricsEnrichmentInterceptorTest.java    From datawave with Apache License 2.0 4 votes vote down vote up
@Test
public void testWrite_UncheckedException() throws Exception {
    QueryMetricsEnrichmentInterceptor subject = new QueryMetricsEnrichmentInterceptor();
    
    // Simulate the initial context
    TestInitialContextFactory.INITIAL_CONTEXT = this.initialContext;
    
    final Capture<QueryCall> qcCapture = Capture.newInstance();
    
    // Set expectations for the postProcess
    expect(responseContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.keySet()).andReturn(new HashSet<>());
    expect(responseContext.getStatus()).andReturn(HttpResponseCodes.SC_OK);
    expect(responseContext.getJaxrsResponse()).andReturn(jaxrsResponse);
    requestContext.setProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")), anyObject());
    expect(jaxrsResponse.getAnnotations()).andReturn(new Annotation[] {enrichQueryMetrics});
    PowerMock.mockStaticPartial(FindAnnotation.class, "findAnnotation");
    expect(FindAnnotation.findAnnotation(isA(Annotation[].class), eq(EnrichQueryMetrics.class))).andReturn(this.enrichQueryMetrics);
    expect(responseContext.getEntity()).andReturn(baseQueryResponse);
    expect(enrichQueryMetrics.methodType()).andReturn(EnrichQueryMetrics.MethodType.CREATE);
    expect(baseQueryResponse.getQueryId()).andReturn(UUID.randomUUID().toString());
    requestContext.setProperty(eq(QueryCall.class.getName()), capture(qcCapture));
    
    // Set expectations for the write
    expect(writerContext.getOutputStream()).andReturn(outputStream);
    writerContext.setOutputStream(isA(CountingOutputStream.class));
    writerContext.setOutputStream(outputStream);
    expect(writerContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.entrySet()).andReturn(new HashSet<>());
    writerContext.proceed();
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")))).andReturn(null);
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "REQUEST_STATS_NAME")))).andReturn(null);
    expect(writerContext.getProperty(QueryCall.class.getName())).andAnswer((IAnswer<QueryCall>) qcCapture::getValue);
    expect(queryCache.get(isA(String.class))).andReturn(runningQuery);
    expect(runningQuery.getLogic()).andReturn(queryLogic);
    expect(queryLogic.getCollectQueryMetrics()).andReturn(true);
    expect(runningQuery.getMetric()).andThrow(new IllegalStateException("INTENTIONALLY THROWN UNCHECKED TEST EXCEPTION"));
    
    // Run the test
    PowerMock.replayAll();
    
    try {
        // Set the initial context factory
        System.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, TestInitialContextFactory.class.getName());
        
        // Create and test the test subject
        setInternalState(subject, QueryCache.class, queryCache);
        setInternalState(subject, QueryMetricsBean.class, queryMetrics);
        subject.filter(requestContext, responseContext);
        subject.aroundWriteTo(writerContext);
    } finally {
        // Remove the initial context factory
        System.clearProperty(InitialContext.INITIAL_CONTEXT_FACTORY);
    }
    PowerMock.verifyAll();
}
 
Example 10
Source File: QueryMetricsEnrichmentInterceptorTest.java    From datawave with Apache License 2.0 4 votes vote down vote up
@Test
public void testWrite_CreateQidResponse() throws Exception {
    QueryMetricsEnrichmentInterceptor subject = new QueryMetricsEnrichmentInterceptor();
    
    // Simulate the initial context
    TestInitialContextFactory.INITIAL_CONTEXT = this.initialContext;
    
    final Capture<QueryCall> qcCapture = Capture.newInstance();
    
    // Set expectations for the postProcess
    expect(responseContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.keySet()).andReturn(new HashSet<>());
    expect(responseContext.getStatus()).andReturn(HttpResponseCodes.SC_OK);
    expect(responseContext.getJaxrsResponse()).andReturn(jaxrsResponse);
    requestContext.setProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")), anyObject());
    expect(jaxrsResponse.getAnnotations()).andReturn(new Annotation[] {enrichQueryMetrics});
    PowerMock.mockStaticPartial(FindAnnotation.class, "findAnnotation");
    expect(FindAnnotation.findAnnotation(isA(Annotation[].class), eq(EnrichQueryMetrics.class))).andReturn(this.enrichQueryMetrics);
    expect(responseContext.getEntity()).andReturn(baseQueryResponse);
    expect(enrichQueryMetrics.methodType()).andReturn(EnrichQueryMetrics.MethodType.CREATE);
    expect(baseQueryResponse.getQueryId()).andReturn(UUID.randomUUID().toString());
    requestContext.setProperty(eq(QueryCall.class.getName()), capture(qcCapture));
    
    // Set expectations for the write
    expect(writerContext.getOutputStream()).andReturn(outputStream);
    writerContext.setOutputStream(isA(CountingOutputStream.class));
    writerContext.setOutputStream(outputStream);
    expect(writerContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.entrySet()).andReturn(new HashSet<>());
    writerContext.proceed();
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")))).andReturn(null);
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "REQUEST_STATS_NAME")))).andReturn(null);
    expect(writerContext.getProperty(QueryCall.class.getName())).andAnswer((IAnswer<QueryCall>) qcCapture::getValue);
    expect(queryCache.get(isA(String.class))).andReturn(runningQuery);
    expect(runningQuery.getLogic()).andReturn(queryLogic);
    expect(queryLogic.getCollectQueryMetrics()).andReturn(true);
    expect(runningQuery.getMetric()).andReturn(queryMetric);
    queryMetric.setCreateCallTime(gt(-2L));
    queryMetric.setLoginTime(-1L);
    queryMetrics.updateMetric(queryMetric);
    
    // Run the test
    PowerMock.replayAll();
    
    try {
        // Set the initial context factory
        System.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, TestInitialContextFactory.class.getName());
        
        // Create and test the test subject
        setInternalState(subject, QueryCache.class, queryCache);
        setInternalState(subject, QueryMetricsBean.class, queryMetrics);
        subject.filter(requestContext, responseContext);
        subject.aroundWriteTo(writerContext);
    } finally {
        // Remove the initial context factory
        System.clearProperty(InitialContext.INITIAL_CONTEXT_FACTORY);
    }
    PowerMock.verifyAll();
}
 
Example 11
Source File: QueryMetricsEnrichmentInterceptorTest.java    From datawave with Apache License 2.0 4 votes vote down vote up
@Test
public void testWrite_CreateAndNextQidResponse() throws Exception {
    QueryMetricsEnrichmentInterceptor subject = new QueryMetricsEnrichmentInterceptor();
    
    // Simulate the initial context
    TestInitialContextFactory.INITIAL_CONTEXT = this.initialContext;
    
    final Capture<QueryCall> qcCapture = Capture.newInstance();
    
    // Set expectations for the postProcess
    expect(responseContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.keySet()).andReturn(new HashSet<>());
    expect(responseContext.getStatus()).andReturn(HttpResponseCodes.SC_OK);
    expect(responseContext.getJaxrsResponse()).andReturn(jaxrsResponse);
    requestContext.setProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")), anyObject());
    expect(jaxrsResponse.getAnnotations()).andReturn(new Annotation[] {enrichQueryMetrics});
    PowerMock.mockStaticPartial(FindAnnotation.class, "findAnnotation");
    expect(FindAnnotation.findAnnotation(isA(Annotation[].class), eq(EnrichQueryMetrics.class))).andReturn(this.enrichQueryMetrics);
    expect(responseContext.getEntity()).andReturn(baseQueryResponse);
    expect(enrichQueryMetrics.methodType()).andReturn(EnrichQueryMetrics.MethodType.CREATE_AND_NEXT);
    expect(baseQueryResponse.getQueryId()).andReturn(UUID.randomUUID().toString());
    requestContext.setProperty(eq(QueryCall.class.getName()), capture(qcCapture));
    
    // Set expectations for the write
    expect(writerContext.getOutputStream()).andReturn(outputStream);
    writerContext.setOutputStream(isA(CountingOutputStream.class));
    writerContext.setOutputStream(outputStream);
    expect(writerContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.entrySet()).andReturn(new HashSet<>());
    writerContext.proceed();
    expect(writerContext.getProperty(QueryCall.class.getName())).andAnswer((IAnswer<QueryCall>) qcCapture::getValue);
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")))).andReturn(null);
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "REQUEST_STATS_NAME")))).andReturn(null);
    expect(queryCache.get(isA(String.class))).andReturn(runningQuery);
    expect(runningQuery.getLogic()).andReturn(queryLogic);
    expect(queryLogic.getCollectQueryMetrics()).andReturn(true);
    expect(runningQuery.getMetric()).andReturn(queryMetric);
    expect(queryMetric.getPageTimes()).andReturn(Arrays.asList(pageTime));
    queryMetric.setCreateCallTime(eq(-1L));
    queryMetric.setLoginTime(-1L);
    pageTime.setCallTime(-1L);
    pageTime.setLoginTime(-1L);
    pageTime.setSerializationTime(geq(0L));
    pageTime.setBytesWritten(0L);
    queryMetrics.updateMetric(queryMetric);
    
    // Run the test
    PowerMock.replayAll();
    
    try {
        // Set the initial context factory
        System.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, TestInitialContextFactory.class.getName());
        
        // Create and test the test subject
        setInternalState(subject, QueryCache.class, queryCache);
        setInternalState(subject, QueryMetricsBean.class, queryMetrics);
        subject.filter(requestContext, responseContext);
        subject.aroundWriteTo(writerContext);
    } finally {
        // Remove the initial context factory
        System.clearProperty(InitialContext.INITIAL_CONTEXT_FACTORY);
    }
    PowerMock.verifyAll();
}
 
Example 12
Source File: QueryMetricsEnrichmentInterceptorTest.java    From datawave with Apache License 2.0 4 votes vote down vote up
@Test
public void testWrite_NextQidResponse() throws Exception {
    QueryMetricsEnrichmentInterceptor subject = new QueryMetricsEnrichmentInterceptor();
    
    // Simulate the initial context
    TestInitialContextFactory.INITIAL_CONTEXT = this.initialContext;
    
    final Capture<QueryCall> qcCapture = Capture.newInstance();
    
    // Set expectations for the postProcess
    expect(responseContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.keySet()).andReturn(new HashSet<>());
    expect(responseContext.getStatus()).andReturn(HttpResponseCodes.SC_OK);
    expect(responseContext.getJaxrsResponse()).andReturn(jaxrsResponse);
    requestContext.setProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")), anyObject());
    expect(jaxrsResponse.getAnnotations()).andReturn(new Annotation[] {enrichQueryMetrics});
    PowerMock.mockStaticPartial(FindAnnotation.class, "findAnnotation");
    expect(FindAnnotation.findAnnotation(isA(Annotation[].class), eq(EnrichQueryMetrics.class))).andReturn(this.enrichQueryMetrics);
    expect(responseContext.getEntity()).andReturn(baseQueryResponse);
    expect(enrichQueryMetrics.methodType()).andReturn(EnrichQueryMetrics.MethodType.NEXT);
    expect(baseQueryResponse.getQueryId()).andReturn(UUID.randomUUID().toString());
    requestContext.setProperty(eq(QueryCall.class.getName()), capture(qcCapture));
    
    // Set expectations for the write
    expect(writerContext.getOutputStream()).andReturn(outputStream);
    writerContext.setOutputStream(isA(CountingOutputStream.class));
    writerContext.setOutputStream(outputStream);
    expect(writerContext.getHeaders()).andReturn(writeHeaders);
    expect(writeHeaders.entrySet()).andReturn(new HashSet<>());
    writerContext.proceed();
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "RESPONSE_STATS_NAME")))).andReturn(null);
    expect(writerContext.getProperty(eq((String) Whitebox.getInternalState(subject, "REQUEST_STATS_NAME")))).andReturn(null);
    expect(writerContext.getProperty(QueryCall.class.getName())).andAnswer((IAnswer<QueryCall>) qcCapture::getValue);
    expect(queryCache.get(isA(String.class))).andReturn(runningQuery);
    expect(runningQuery.getLogic()).andReturn(queryLogic);
    expect(queryLogic.getCollectQueryMetrics()).andReturn(true);
    expect(runningQuery.getMetric()).andReturn(queryMetric);
    expect(queryMetric.getPageTimes()).andReturn(Arrays.asList(pageTime));
    pageTime.setCallTime(-1L);
    pageTime.setLoginTime(-1L);
    pageTime.setSerializationTime(geq(0L));
    pageTime.setBytesWritten(0L);
    queryMetrics.updateMetric(queryMetric);
    
    // Run the test
    PowerMock.replayAll();
    
    try {
        // Set the initial context factory
        System.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, TestInitialContextFactory.class.getName());
        
        // Create and test the test subject
        setInternalState(subject, QueryCache.class, queryCache);
        setInternalState(subject, QueryMetricsBean.class, queryMetrics);
        subject.filter(requestContext, responseContext);
        subject.aroundWriteTo(writerContext);
    } finally {
        // Remove the initial context factory
        System.clearProperty(InitialContext.INITIAL_CONTEXT_FACTORY);
    }
    PowerMock.verifyAll();
}
 
Example 13
Source File: AnnotationManagerTest.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  selectionAnnotationStore = new AnnotationStore<>();
  contributionAnnotationQueue = new AnnotationQueue<>(MAX_CONTRIBUTION_ANNOTATIONS);

  /*
   * Mock annotation store CTOR calls to return an object we hold a reference to.
   * This is necessary to access the inner state of the annotation manager for testing.
   */
  PowerMock.expectNew(AnnotationStore.class).andReturn(selectionAnnotationStore);
  PowerMock.expectNew(AnnotationQueue.class, MAX_CONTRIBUTION_ANNOTATIONS)
      .andReturn(contributionAnnotationQueue);

  PowerMock.replayAll();

  annotationManager = new AnnotationManager();

  file = EasyMock.createNiceMock(IFile.class);
  user = EasyMock.createNiceMock(User.class);
  user2 = EasyMock.createNiceMock(User.class);
  editor = EasyMock.createNiceMock(Editor.class);

  selectionTextAttributes = EasyMock.createNiceMock(TextAttributes.class);
  caretTextAttributes = EasyMock.createNiceMock(TextAttributes.class);
  contributionTextAttributes = EasyMock.createNiceMock(TextAttributes.class);

  PowerMock.mockStaticPartial(
      SelectionAnnotation.class, "getSelectionTextAttributes", "getCaretTextAttributes");

  PowerMock.expectPrivate(SelectionAnnotation.class, "getSelectionTextAttributes", editor, user)
      .andStubReturn(selectionTextAttributes);
  PowerMock.expectPrivate(SelectionAnnotation.class, "getSelectionTextAttributes", editor, user2)
      .andStubReturn(selectionTextAttributes);

  PowerMock.expectPrivate(SelectionAnnotation.class, "getCaretTextAttributes", editor, user)
      .andStubReturn(caretTextAttributes);
  PowerMock.expectPrivate(SelectionAnnotation.class, "getCaretTextAttributes", editor, user2)
      .andStubReturn(caretTextAttributes);

  PowerMock.mockStaticPartial(ContributionAnnotation.class, "getContributionTextAttributes");

  PowerMock.expectPrivate(
          ContributionAnnotation.class, "getContributionTextAttributes", editor, user)
      .andStubReturn(contributionTextAttributes);
  PowerMock.expectPrivate(
          ContributionAnnotation.class, "getContributionTextAttributes", editor, user2)
      .andStubReturn(contributionTextAttributes);

  PowerMock.replay(SelectionAnnotation.class, ContributionAnnotation.class);
}
 
Example 14
Source File: EclipseMocker.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
public static void mockSWTDisplay() {
  PowerMock.mockStaticPartial(SWTUtils.class, "getDisplay");
  EasyMock.expect(SWTUtils.getDisplay()).andStubReturn(null);
  PowerMock.replay(SWTUtils.class);
}
 
Example 15
Source File: AnnotationManagerTest.java    From saros with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Must be called before the first call to {@link
 * #mockAddRangeHighlightersWithGivenRangeHighlighters(List, TextAttributes, IFile)} or {@link
 * #mockAddRemoveRangeHighlighters(List, IFile, Editor, TextAttributes)}.
 */
private void prepareMockAddRemoveRangeHighlighters() {
  PowerMock.mockStaticPartial(
      AbstractEditorAnnotation.class, "addRangeHighlighter", "removeRangeHighlighter");
}