下面列出了怎么用org.mockito.MockitoAnnotations的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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();
}
@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));
}
@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);
}
@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();
}
@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));
}
@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);
}
@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();
}
@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();
}
@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());
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
cleanUpService = new CleanUpService(scheduledExecutorService, clientSessionPersistence,
subscriptionPersistence, retainedMessagePersistence, clientQueuePersistence);
InternalConfigurations.PERSISTENCE_BUCKET_COUNT.set(64);
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(pool.takeNextId()).thenReturn(100);
when(pools.forClientOrNull(anyString())).thenReturn(pool);
embeddedChannel = new EmbeddedChannel(new ReturnMessageIdToPoolHandler(pools));
embeddedChannel.attr(ChannelAttributes.CLIENT_ID).set("clientId");
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(spanProcessor1.isStartRequired()).thenReturn(true);
when(spanProcessor1.isEndRequired()).thenReturn(true);
when(spanProcessor2.isStartRequired()).thenReturn(true);
when(spanProcessor2.isEndRequired()).thenReturn(true);
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Properties properties = new Properties();
properties.setProperty("traverser.test.pollRequest.queue", "");
properties.setProperty("traverser.test.pollRequest.statuses", "");
properties.setProperty("traverser.test.hostload", "2");
properties.setProperty("traverser.test.timeout", "60");
properties.setProperty("traverser.test.timeunit", "SECONDS");
setupConfig.initConfig(properties);
}
@Before public void setUp() {
MockitoAnnotations.initMocks(this);
Fixtures.loadModel(TWELVE_ZONE_DEVICE_JSON);
source = new SettableModelSource<>();
devices = DeviceModelProvider.instance().getModels(ImmutableSet.of(TWELVE_ZONE_DEVICE_ADDRESS));
controller = new LawnAndGardenDeviceMoreController(source, devices, client());
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final SolutionSharedResource solutionSharedResource = new SolutionSharedResource(solutionSharedRepository);
this.restSolutionSharedMockMvc = MockMvcBuilders.standaloneSetup(solutionSharedResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(securityConfigurationService.allowRequestProblemInformation()).thenReturn(true);
encoder = new Mqtt5PubrecEncoder(messageDroppedService, securityConfigurationService);
super.setUp(encoder);
}
@Before public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
source = new SettableModelSource<>();
controller = new CareBehaviorTemplateListController(source);
callback = Mockito.mock(CareBehaviorTemplateListController.Callback.class);
controller.setCallback(callback);
expectRequestOfType(CareSubsystem.ListBehaviorsRequest.NAME)
.andRespondFromPath("subsystems/care/listBehaviorsResponse.json");
expectRequestOfType(CareSubsystem.ListBehaviorTemplatesRequest.NAME)
.andRespondFromPath("subsystems/care/listBehaviorTemplatesResponse.json");
}
@Before
public void setup() throws Http2Exception {
MockitoAnnotations.initMocks(this);
// Assume we always write all the allocated bytes.
doAnswer(writeAnswer(false)).when(writer).write(any(Http2Stream.class), anyInt());
setup(-1);
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
LogsResource logsResource = new LogsResource();
this.restLogsMockMvc = MockMvcBuilders
.standaloneSetup(logsResource)
.build();
}
@Before
public void before() {
MockitoAnnotations.initMocks(this);
InternalConfigurations.PLUGIN_TASK_QUEUE_EXECUTOR_COUNT.set(2);
executorService =
new PluginTaskExecutorServiceImpl(new ExecutorProvider(Lists.newArrayList(executor1, executor2)),
mock(ShutdownHooks.class));
}
@Before
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
InternalConfigurations.PERSISTENCE_CLOSE_RETRIES.set(3);
InternalConfigurations.PERSISTENCE_CLOSE_RETRY_INTERVAL.set(5);
InternalConfigurations.PERSISTENCE_BUCKET_COUNT.set(BUCKET_COUNT);
when(localPersistenceFileUtil.getVersionedLocalPersistenceFolder(anyString(), anyString())).thenReturn(
temporaryFolder.newFolder());
metricRegistry = new MetricRegistry();
persistence = new ClientSessionMemoryLocalPersistence(payloadPersistence, metricRegistry, eventLog);
memoryGauge = metricRegistry.gauge(HiveMQMetrics.CLIENT_SESSIONS_MEMORY_PERSISTENCE_TOTAL_SIZE.name(), null);
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
// Use a cached thread pool as we need a thread for each blocked call
otherWork = Executors.newCachedThreadPool();
channel = InProcessChannelBuilder.forName("channel").executor(otherWork).build();
blockingStub = TestServiceGrpc.newBlockingStub(channel);
asyncStub = TestServiceGrpc.newStub(channel);
futureStub = TestServiceGrpc.newFutureStub(channel);
}
/** Set up for test. */
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(channel.pipeline()).thenReturn(pipeline);
when(channel.eventLoop()).thenReturn(eventLoop);
when(channel.newPromise()).thenReturn(new DefaultChannelPromise(channel));
when(channel.voidPromise()).thenReturn(new DefaultChannelPromise(channel));
ChannelPromise completedPromise = new DefaultChannelPromise(channel)
.setSuccess();
when(channel.write(any())).thenReturn(completedPromise);
when(channel.writeAndFlush(any())).thenReturn(completedPromise);
when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(completedPromise);
when(pipeline.firstContext()).thenReturn(ctx);
when(eventLoop.inEventLoop()).thenReturn(true);
when(http2Stream.id()).thenReturn(STREAM_ID);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Runnable runnable = (Runnable) invocation.getArguments()[0];
runnable.run();
return null;
}
}).when(eventLoop).execute(any(Runnable.class));
stream = createStream();
}