org.mockito.MockitoAnnotations Java Examples

The following examples show how to use org.mockito.MockitoAnnotations. 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: ConnectHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

    MockitoAnnotations.initMocks(this);
    when(clientSessionPersistence.isExistent(anyString())).thenReturn(false);
    when(clientSessionPersistence.clientConnected(anyString(), anyBoolean(), anyLong(), any())).thenReturn(Futures.immediateFuture(null));

    embeddedChannel = new EmbeddedChannel(new DummyHandler());

    configurationService = new TestConfigurationBootstrap().getFullConfigurationService();
    InternalConfigurations.AUTH_DENY_UNAUTHENTICATED_CONNECTIONS.set(false);
    final MqttConnackSendUtil connackSendUtil = new MqttConnackSendUtil(eventLog);
    mqttConnacker = new MqttConnacker(connackSendUtil);

    when(channelPersistence.get(anyString())).thenReturn(null);

    when(channelDependencies.getAuthInProgressMessageHandler()).thenReturn(
            new AuthInProgressMessageHandler(mqttConnacker));

    defaultPermissions = new ModifiableDefaultPermissionsImpl();

    buildPipeline();
}
 
Example #2
Source File: RetainedMessageTypeMigrationTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    dataFolder = temporaryFolder.newFolder();
    when(systemInformation.getDataFolder()).thenReturn(dataFolder);
    when(systemInformation.getConfigFolder()).thenReturn(temporaryFolder.newFolder());
    when(systemInformation.getHiveMQVersion()).thenReturn("2019.2");
    configurationService = ConfigurationBootstrap.bootstrapConfig(systemInformation);

    InternalConfigurations.PERSISTENCE_BUCKET_COUNT.set(4);
    InternalConfigurations.PAYLOAD_PERSISTENCE_BUCKET_COUNT.set(4);

    final File file = new File(dataFolder, LocalPersistenceFileUtil.PERSISTENCE_SUBFOLDER_NAME);
    file.mkdirs();
    new File(file, RetainedMessageLocalPersistence.PERSISTENCE_NAME).mkdir();
    new File(file, PublishPayloadLocalPersistence.PERSISTENCE_NAME).mkdir();

    callback = new RetainedMessageTypeMigration.RetainedMessagePersistenceTypeSwitchCallback(4,
            payloadLocalPersistence,
            rocksDBLocalPersistence,
            payloadExceptionLogging);

}
 
Example #3
Source File: PubcompInterceptorHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    executor1 = new PluginTaskExecutor(new AtomicLong());
    executor1.postConstruct();

    channel = new EmbeddedChannel();
    channel.attr(ChannelAttributes.CLIENT_ID).set("client");
    channel.attr(ChannelAttributes.REQUEST_RESPONSE_INFORMATION).set(true);
    channel.attr(ChannelAttributes.PLUGIN_CLIENT_CONTEXT).set(clientContext);
    when(plugin.getId()).thenReturn("plugin");

    final FullConfigurationService configurationService =
            new TestConfigurationBootstrap().getFullConfigurationService();
    final PluginOutPutAsyncer asyncer = new PluginOutputAsyncerImpl(mock(ShutdownHooks.class));
    final PluginTaskExecutorService pluginTaskExecutorService = new PluginTaskExecutorServiceImpl(() -> executor1, mock(ShutdownHooks.class));

    handler = new PubcompInterceptorHandler(configurationService, asyncer, hiveMQExtensions,
            pluginTaskExecutorService);
    channel.pipeline().addFirst(handler);
}
 
Example #4
Source File: PassthroughSoftwareRendererShould.java    From LiTr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
    bufferInfo.set(FRAME_OFFSET, FRAME_SIZE, FRAME_PRESENTATION_TIME, 0);

    ByteBuffer inputBuffer = ByteBuffer.allocate(FRAME_SIZE);
    for (int index = 0; index < FRAME_SIZE; index++) {
        inputBuffer.put((byte) index);
    }

    frame = new Frame(
            0,
            inputBuffer,
            bufferInfo);

    renderer = new PassthroughSoftwareRenderer(encoder);
}
 
Example #5
Source File: ProfileInfoResourceIntTest.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    String mockProfile[] = { "test" };
    JHipsterProperties.Ribbon ribbon = new JHipsterProperties.Ribbon();
    ribbon.setDisplayOnActiveProfiles(mockProfile);
    when(jHipsterProperties.getRibbon()).thenReturn(ribbon);

    String activeProfiles[] = {"test"};
    when(environment.getDefaultProfiles()).thenReturn(activeProfiles);
    when(environment.getActiveProfiles()).thenReturn(activeProfiles);

    ProfileInfoResource profileInfoResource = new ProfileInfoResource(environment, jHipsterProperties);
    this.restProfileMockMvc = MockMvcBuilders
        .standaloneSetup(profileInfoResource)
        .build();
}
 
Example #6
Source File: UniformStreamByteDistributorTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Http2Exception {
    MockitoAnnotations.initMocks(this);

    stateMap = new IntObjectHashMap<TestStreamByteDistributorStreamState>();
    connection = new DefaultHttp2Connection(false);
    distributor = new UniformStreamByteDistributor(connection);

    // Assume we always write all the allocated bytes.
    resetWriter();

    connection.local().createStream(STREAM_A, false);
    connection.local().createStream(STREAM_B, false);
    Http2Stream streamC = connection.local().createStream(STREAM_C, false);
    Http2Stream streamD = connection.local().createStream(STREAM_D, false);
    setPriority(streamC.id(), STREAM_A, DEFAULT_PRIORITY_WEIGHT, false);
    setPriority(streamD.id(), STREAM_A, DEFAULT_PRIORITY_WEIGHT, false);
}
 
Example #7
Source File: DefaultHttp2RemoteFlowControllerTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Http2Exception {
    MockitoAnnotations.initMocks(this);

    when(ctx.newPromise()).thenReturn(promise);
    when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden"));
    setChannelWritability(true);
    when(channel.config()).thenReturn(config);
    when(executor.inEventLoop()).thenReturn(true);

    initConnectionAndController();

    resetCtx();
    // This is intentionally left out of initConnectionAndController so it can be tested below.
    controller.channelHandlerContext(ctx);
    assertWritabilityChanged(1, true);
    reset(listener);
}
 
Example #8
Source File: SubscriptionMethodReturnValueHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	MockitoAnnotations.initMocks(this);

	SimpMessagingTemplate messagingTemplate = new SimpMessagingTemplate(this.messageChannel);
	messagingTemplate.setMessageConverter(new StringMessageConverter());
	this.handler = new SubscriptionMethodReturnValueHandler(messagingTemplate);

	SimpMessagingTemplate jsonMessagingTemplate = new SimpMessagingTemplate(this.messageChannel);
	jsonMessagingTemplate.setMessageConverter(new MappingJackson2MessageConverter());
	this.jsonHandler = new SubscriptionMethodReturnValueHandler(jsonMessagingTemplate);

	Method method = this.getClass().getDeclaredMethod("getData");
	this.subscribeEventReturnType = new MethodParameter(method, -1);

	method = this.getClass().getDeclaredMethod("getDataAndSendTo");
	this.subscribeEventSendToReturnType = new MethodParameter(method, -1);

	method = this.getClass().getDeclaredMethod("handle");
	this.messageMappingReturnType = new MethodParameter(method, -1);

	method = this.getClass().getDeclaredMethod("getJsonView");
	this.subscribeEventJsonViewReturnType = new MethodParameter(method, -1);
}
 
Example #9
Source File: AccountResourceIT.java    From alchemy with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);
    doNothing().when(mockMailService).sendActivationEmail(any());
    AccountResource accountResource =
        new AccountResource(userRepository, userService, mockMailService);

    AccountResource accountUserMockResource =
        new AccountResource(userRepository, mockUserService, mockMailService);
    this.restMvc = MockMvcBuilders.standaloneSetup(accountResource)
        .setMessageConverters(httpMessageConverters)
        .setControllerAdvice(exceptionTranslator)
        .build();
    this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource)
        .setControllerAdvice(exceptionTranslator)
        .build();
}
 
Example #10
Source File: NettyServerHandlerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  when(streamTracerFactory.newServerStreamTracer(anyString(), any(Metadata.class)))
      .thenReturn(streamTracer);

  doAnswer(
        new Answer<Void>() {
          @Override
          public Void answer(InvocationOnMock invocation) throws Throwable {
            StreamListener.MessageProducer producer =
                (StreamListener.MessageProducer) invocation.getArguments()[0];
            InputStream message;
            while ((message = producer.next()) != null) {
              streamListenerMessageQueue.add(message);
            }
            return null;
          }
        })
    .when(streamListener)
    .messagesAvailable(any(StreamListener.MessageProducer.class));
}
 
Example #11
Source File: ProfileInfoResourceIntTest.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    String mockProfile[] = { "test" };
    JHipsterProperties.Ribbon ribbon = new JHipsterProperties.Ribbon();
    ribbon.setDisplayOnActiveProfiles(mockProfile);
    when(jHipsterProperties.getRibbon()).thenReturn(ribbon);

    String activeProfiles[] = {"test"};
    when(environment.getDefaultProfiles()).thenReturn(activeProfiles);
    when(environment.getActiveProfiles()).thenReturn(activeProfiles);

    ProfileInfoResource profileInfoResource = new ProfileInfoResource(environment, jHipsterProperties);
    this.restProfileMockMvc = MockMvcBuilders
        .standaloneSetup(profileInfoResource)
        .build();
}
 
Example #12
Source File: PublishPayloadTypeMigrationTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws IOException {
    MockitoAnnotations.initMocks(this);
    dataFolder = temporaryFolder.newFolder();
    when(systemInformation.getDataFolder()).thenReturn(dataFolder);
    when(systemInformation.getConfigFolder()).thenReturn(temporaryFolder.newFolder());
    when(systemInformation.getHiveMQVersion()).thenReturn("2019.2");

    InternalConfigurations.PERSISTENCE_BUCKET_COUNT.set(4);
    InternalConfigurations.PAYLOAD_PERSISTENCE_BUCKET_COUNT.set(4);
    final File file = new File(dataFolder, LocalPersistenceFileUtil.PERSISTENCE_SUBFOLDER_NAME);
    file.mkdirs();
    new File(file, RetainedMessageLocalPersistence.PERSISTENCE_NAME).mkdir();
    new File(file, PublishPayloadLocalPersistence.PERSISTENCE_NAME).mkdir();

    configurationService = ConfigurationBootstrap.bootstrapConfig(systemInformation);
}
 
Example #13
Source File: PickFirstLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  for (int i = 0; i < 3; i++) {
    SocketAddress addr = new FakeSocketAddress("server" + i);
    servers.add(new EquivalentAddressGroup(addr));
    socketAddresses.add(addr);
  }

  when(mockSubchannel.getAllAddresses()).thenThrow(new UnsupportedOperationException());
  when(mockHelper.createSubchannel(
      anyListOf(EquivalentAddressGroup.class), any(Attributes.class)))
      .thenReturn(mockSubchannel);

  loadBalancer = new PickFirstLoadBalancer(mockHelper);
}
 
Example #14
Source File: TlsTcpChannelInitializerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
    MockitoAnnotations.initMocks(this);

    pipeline = new FakeChannelPipeline();

    when(tlsTcpListener.getTls()).thenReturn(tls);
    when(ssl.getSslHandler(any(SocketChannel.class), any(Tls.class))).thenReturn(sslHandler);
    when(sslHandler.handshakeFuture()).thenReturn(future);
    when(socketChannel.pipeline()).thenReturn(pipeline);
    when(socketChannel.attr(any(AttributeKey.class))).thenReturn(attribute);
    when(channelDependencies.getConfigurationService()).thenReturn(fullConfigurationService);

    tlstcpChannelInitializer = new TlsTcpChannelInitializer(channelDependencies, tlsTcpListener, ssl, eventLog);

}
 
Example #15
Source File: TimeTest.java    From acelera-dev-sp-2019 with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setup(){
    Jogador allejo = mock("Allejo", 1000, Posicao.ATAQUE);
    Jogador gomez = mock("Gomez", 2, Posicao.ATAQUE);
    Jogador rivaldo = mock("Rivaldo", 23, Posicao.ATAQUE);
    Jogador neymar = mock("Neymar", 33, Posicao.ATAQUE);
    Jogador alface = mock("Alface", -1, Posicao.GOLEIRO);
    Jogador dida = mock("Dida", 5, Posicao.GOLEIRO);
    Jogador dasilva = mock("DaSilva", 0, Posicao.GOLEIRO);
    Jogador vincento = mock("Vincento", 2, Posicao.DEFESA);
    Jogador paco = mock("Paco", 1, Posicao.DEFESA);

    List<Jogador> jogadores = Arrays.asList(allejo, gomez, rivaldo, neymar, alface, dida, dasilva, vincento, paco);

    Time brasil = mockTime("Brasil", jogadores, 1L);

    MockitoAnnotations.initMocks(this);

    Mockito.when(timeRepository.findAll()).thenReturn(Arrays.asList(brasil));
    Mockito.when(timeRepository.findById(1L)).thenReturn(Optional.of(brasil));
}
 
Example #16
Source File: MutableHandlerRegistryTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  MethodDescriptor<String, Integer> flowMethod = MethodDescriptor.<String, Integer>newBuilder()
      .setType(MethodType.UNKNOWN)
      .setFullMethodName("basic/flow")
      .setRequestMarshaller(requestMarshaller)
      .setResponseMarshaller(responseMarshaller)
      .build();
  basicServiceDefinition = ServerServiceDefinition.builder(
      new ServiceDescriptor("basic", flowMethod))
      .addMethod(flowMethod, flowHandler)
      .build();

  MethodDescriptor<String, Integer> coupleMethod =
      flowMethod.toBuilder().setFullMethodName("multi/couple").build();
  MethodDescriptor<String, Integer> fewMethod =
      flowMethod.toBuilder().setFullMethodName("multi/few").build();
  multiServiceDefinition = ServerServiceDefinition.builder(
      new ServiceDescriptor("multi", coupleMethod, fewMethod))
      .addMethod(coupleMethod, coupleHandler)
      .addMethod(fewMethod, fewHandler)
      .build();

  flowMethodDefinition = getOnlyElement(basicServiceDefinition.getMethods());
}
 
Example #17
Source File: BusinessResourceIT.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);
    final BusinessResource businessResource = new BusinessResource(businessService);
    this.restBusinessMockMvc = MockMvcBuilders.standaloneSetup(businessResource)
        .setCustomArgumentResolvers(pageableArgumentResolver)
        .setControllerAdvice(exceptionTranslator)
        .setConversionService(createFormattingConversionService())
        .setMessageConverters(jacksonMessageConverter)
        .setValidator(validator).build();
}
 
Example #18
Source File: PublishPayloadXodusLocalPersistenceTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
    MockitoAnnotations.initMocks(this);

    InternalConfigurations.PERSISTENCE_CLOSE_RETRIES.set(3);
    InternalConfigurations.PERSISTENCE_CLOSE_RETRY_INTERVAL.set(5);
    InternalConfigurations.PAYLOAD_PERSISTENCE_BUCKET_COUNT.set(8);
    when(localPersistenceFileUtil.getVersionedLocalPersistenceFolder(anyString(), anyString())).thenReturn(temporaryFolder.newFolder());

    persistence = new PublishPayloadXodusLocalPersistence(localPersistenceFileUtil, new EnvironmentUtil(), new PersistenceStartup());
    persistence.start();
}
 
Example #19
Source File: DefaultHttp2LocalFlowControllerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Http2Exception {
    MockitoAnnotations.initMocks(this);

    when(ctx.newPromise()).thenReturn(promise);
    when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden"));
    when(ctx.executor()).thenReturn(executor);
    when(executor.inEventLoop()).thenReturn(true);

    initController(false);
}
 
Example #20
Source File: DefaultStompSessionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setUp() {
	MockitoAnnotations.initMocks(this);

	this.sessionHandler = mock(StompSessionHandler.class);
	this.connectHeaders = new StompHeaders();
	this.session = new DefaultStompSession(this.sessionHandler, this.connectHeaders);
	this.session.setMessageConverter(new StringMessageConverter());

	SettableListenableFuture<Void> future = new SettableListenableFuture<>();
	future.set(null);
	given(this.connection.send(this.messageCaptor.capture())).willReturn(future);
}
 
Example #21
Source File: DefaultHttp2FrameWriterTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    frameWriter = new DefaultHttp2FrameWriter();

    outbound = Unpooled.buffer();

    expectedOutbound = Unpooled.EMPTY_BUFFER;

    promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);

    http2HeadersEncoder = new DefaultHttp2HeadersEncoder();

    Answer<Object> answer = new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock var1) throws Throwable {
            Object msg = var1.getArgument(0);
            if (msg instanceof ByteBuf) {
                outbound.writeBytes((ByteBuf) msg);
            }
            ReferenceCountUtil.release(msg);
            return future;
        }
    };
    when(ctx.write(any())).then(answer);
    when(ctx.write(any(), any(ChannelPromise.class))).then(answer);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(ctx.channel()).thenReturn(channel);
    when(ctx.executor()).thenReturn(ImmediateEventExecutor.INSTANCE);
}
 
Example #22
Source File: PublishPayloadRocksDBLocalPersistenceTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
    MockitoAnnotations.initMocks(this);

    InternalConfigurations.PAYLOAD_PERSISTENCE_BUCKET_COUNT.set(8);
    when(localPersistenceFileUtil.getVersionedLocalPersistenceFolder(anyString(), anyString())).thenReturn(temporaryFolder.newFolder());

    persistence = new PublishPayloadRocksDBLocalPersistence(localPersistenceFileUtil, new PersistenceStartup());
    persistence.start();
}
 
Example #23
Source File: ExtendedConfigurationTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Before
public void before()
{
    MockitoAnnotations.initMocks(this);
    configuration.setCustomConverters(List.of());
    configuration.setCustomTableTransformers(Map.of());
    configuration.setExamplesTableHeaderSeparator(SEPARATOR);
    configuration.setExamplesTableValueSeparator(SEPARATOR);
}
 
Example #24
Source File: ProductResourceIT.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);
    final ProductResource productResource = new ProductResource(productRepository);
    this.restProductMockMvc = MockMvcBuilders.standaloneSetup(productResource)
        .setCustomArgumentResolvers(pageableArgumentResolver)
        .setControllerAdvice(exceptionTranslator)
        .setConversionService(createFormattingConversionService())
        .setMessageConverters(jacksonMessageConverter)
        .setValidator(validator).build();
}
 
Example #25
Source File: Mqtt5PubcompEncoderTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(securityConfigurationService.allowRequestProblemInformation()).thenReturn(true);

    encoder = new Mqtt5PubCompEncoder(messageDroppedService, securityConfigurationService);
    super.setUp(encoder);
}
 
Example #26
Source File: ServerCallImplTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  context = Context.ROOT.withCancellation();
  call = new ServerCallImpl<Long, Long>(stream, UNARY_METHOD, requestHeaders, context,
      DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(),
      serverCallTracer);
}
 
Example #27
Source File: DefaultHandshakeHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {
	super.setup();

	MockitoAnnotations.initMocks(this);
	this.handshakeHandler = new DefaultHandshakeHandler(this.upgradeStrategy);
}
 
Example #28
Source File: Mqtt5PubackEncoderTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(securityConfigurationService.allowRequestProblemInformation()).thenReturn(true);

    encoder = new Mqtt5PubackEncoder(messageDroppedService, securityConfigurationService);
    super.setUp(encoder);
}
 
Example #29
Source File: DefaultWebClientTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() {
	MockitoAnnotations.initMocks(this);
	this.exchangeFunction = mock(ExchangeFunction.class);
	ClientResponse mockResponse = mock(ClientResponse.class);
	given(this.exchangeFunction.exchange(this.captor.capture())).willReturn(Mono.just(mockResponse));
	this.builder = WebClient.builder().baseUrl("/base").exchangeFunction(this.exchangeFunction);
}
 
Example #30
Source File: LogsResourceIntTest.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    LogsResource logsResource = new LogsResource();
    this.restLogsMockMvc = MockMvcBuilders
        .standaloneSetup(logsResource)
        .build();
}