下面列出了怎么用org.mockito.Answers的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testStopWhileStillStarting() {
final BluetoothGatt bluetoothGatt = Mockito.mock(BluetoothGatt.class, Answers.RETURNS_DEEP_STUBS);
when(device.isConnected()).thenReturn(true);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) {
BluetoothGattCallback callback = invocationOnMock.getArgument(0);
callback.onServicesDiscovered(bluetoothGatt, BluetoothGatt.GATT_SUCCESS);
return null;
}
}).when(device).execute(Mockito.<BluetoothGattCallback>any());
subscription.start();
Robolectric.getForegroundThreadScheduler().pause();
subscription.stop();
subscription.start();
Robolectric.getForegroundThreadScheduler().unPause();
assertTrue(subscription.isStarted());
}
private SslHandler getSslHandler() throws Exception {
// get SslHandler if it was added to the pipeline
ArgumentCaptor<ChannelHandler> captor = ArgumentCaptor.forClass(ChannelHandler.class);
verify(pipeline).addFirst(captor.capture());
SslHandler sslHandler = (SslHandler) captor.getValue();
// mock and store the context so we can get the handshake future
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
when(context.executor()).thenReturn(ImmediateEventExecutor.INSTANCE);
when(context.channel()).thenReturn(mock(Channel.class, Answers.RETURNS_MOCKS.get()));
// add the handler but prevent the handshake from running automatically
when(channel.isActive()).thenReturn(false);
sslHandler.handlerAdded(context);
return sslHandler;
}
public static ExecutionOperator createExecutionOperator(String name, int numInputs, int numOutputs, Platform platform) {
final ExecutionOperator mockedExecutionOperator = mock(ExecutionOperator.class, Answers.CALLS_REAL_METHODS);
when(mockedExecutionOperator.toString()).thenReturn("ExecutionOperator[" + name + "]");
when(mockedExecutionOperator.getPlatform()).thenReturn(platform);
// Mock input slots.
final InputSlot[] inputSlots = new InputSlot[numInputs];
for (int inputIndex = 0; inputIndex < numInputs; inputIndex++) {
inputSlots[inputIndex] = new InputSlot("input-" + inputIndex, mockedExecutionOperator, mock(DataSetType.class));
}
when(mockedExecutionOperator.getAllInputs()).thenReturn(inputSlots);
when(mockedExecutionOperator.getNumInputs()).thenCallRealMethod();
// Mock output slots.
final OutputSlot[] outputSlots = new OutputSlot[numOutputs];
for (int outputIndex = 0; outputIndex < numOutputs; outputIndex++) {
outputSlots[outputIndex] = new OutputSlot("output" + outputIndex, mockedExecutionOperator, mock(DataSetType.class));
}
when(mockedExecutionOperator.getAllOutputs()).thenReturn(outputSlots);
when(mockedExecutionOperator.getNumOutputs()).thenCallRealMethod();
return mockedExecutionOperator;
}
@Test
public void testConstructor_avoidsEclipseWriterBug() throws IOException {
// Due to a bug in Eclipse, we *must* call close on the object returned from openWriter().
// Eclipse proxies a Writer but does not implement the fluent API correctly.
// Here, we implement the fluent Writer API with the same bug:
Writer mockWriter = Mockito.mock(Writer.class, (Answer<?>) invocation -> {
if (Writer.class.isAssignableFrom(invocation.getMethod().getReturnType())) {
// Erroneously return the delegate writer (matching the Eclipse bug!)
return source;
} else {
return Answers.RETURNS_SMART_NULLS.get().answer(invocation);
}
});
when(sourceFile.openWriter()).thenReturn(mockWriter);
FilerUtils.writeCompilationUnit(filer, unit, originatingElement);
verify(mockWriter).close();
}
@Test
void updateWithValidLeaderElectionRecordShouldSendPutRequest() throws Exception {
// Given
final Resource<ConfigMap, ?> configMapResource = configMaps.withName("name");
final Replaceable<ConfigMap, ConfigMap> replaceable = mock(Replaceable.class, Answers.RETURNS_DEEP_STUBS);
when(configMapResource.lockResourceVersion(any())).thenReturn(replaceable);
final ConfigMap configMapInTheCluster = new ConfigMap();
configMapInTheCluster.setMetadata(new ObjectMetaBuilder().withAnnotations(new HashMap<>()).build());
when(configMapResource.get()).thenReturn(configMapInTheCluster);
final LeaderElectionRecord record = new LeaderElectionRecord(
"1337", Duration.ofSeconds(1), ZonedDateTime.now(), ZonedDateTime.now(), 0);
record.setVersion("313373");
final ConfigMapLock lock = new ConfigMapLock("namespace", "name", "1337");
// When
lock.update(kc, record);
// Then
verify(replaceable, times(1)).replace(eq(configMapInTheCluster));
}
@Test
void updateWithValidLeaderElectionRecordShouldSendPutRequest() throws Exception {
// Given
final Resource<Lease, ?> leaseResource = leases.withName("name");
final Replaceable<Lease, Lease> replaceable = mock(Replaceable.class, Answers.RETURNS_DEEP_STUBS);
when(leaseResource.lockResourceVersion(any())).thenReturn(replaceable);
final Lease leaseInTheCluster = new Lease();
leaseInTheCluster.setSpec(new LeaseSpec());
when(leaseResource.get()).thenReturn(leaseInTheCluster);
final LeaderElectionRecord record = new LeaderElectionRecord(
"1337", Duration.ofSeconds(1), ZonedDateTime.now(), ZonedDateTime.now(), 0);
record.setVersion("313373");
final LeaseLock lock = new LeaseLock("namespace", "name", "1337");
// When
lock.update(kc, record);
// Then
verify(replaceable, times(1)).replace(eq(leaseInTheCluster));
assertEquals("1337", leaseInTheCluster.getSpec().getHolderIdentity());
}
@Test
public void testRank() throws Exception {
XAStore.Provider provider = new XAStore.Provider();
XAStoreConfiguration configuration = new XAStoreConfiguration("testXAResourceId");
ServiceLocator serviceLocator = dependencySet()
.with(provider)
.with(Store.Provider.class)
.with(mock(DiskResourceService.class))
.with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS))
.with(mock(TransactionManagerProvider.class)).build();
serviceLocator.startAllServices();
Set<ServiceConfiguration<?, ?>> xaStoreConfigs = Collections.singleton(configuration);
assertThat(provider.wrapperStoreRank(xaStoreConfigs), is(1));
Set<ServiceConfiguration<?, ?>> emptyConfigs = emptySet();
assertThat(provider.wrapperStoreRank(emptyConfigs), is(0));
}
@Test
public void testProvidingOffHeapDiskStoreConfiguration() throws Exception {
OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();
ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider)
.with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build();
serviceLocator.startAllServices();
CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class);
when(cacheConfiguration.getResourcePools()).thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build());
PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache", cacheConfiguration);
@SuppressWarnings("unchecked")
Store.Configuration<Long, Object[]> storeConfig1 = MockitoUtil.mock(Store.Configuration.class);
when(storeConfig1.getKeyType()).thenReturn(Long.class);
when(storeConfig1.getValueType()).thenReturn(Object[].class);
when(storeConfig1.getResourcePools()).thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder()
.disk(10, MB)
.build());
when(storeConfig1.getDispatcherConcurrency()).thenReturn(1);
OffHeapDiskStore<Long, Object[]> offHeapDiskStore1 = provider.createStore(
storeConfig1, space, new OffHeapDiskStoreConfiguration("pool", 2, 4));
assertThat(offHeapDiskStore1.getThreadPoolAlias(), is("pool"));
assertThat(offHeapDiskStore1.getWriterConcurrency(), is(2));
assertThat(offHeapDiskStore1.getDiskSegments(), is(4));
}
@Test
public void testSupportsMultipleAuthoritativeTierProviders() throws Exception {
ServiceLocator.DependencySet dependencySet = dependencySet();
OnHeapStore.Provider cachingTierProvider = new OnHeapStore.Provider();
OffHeapStore.Provider authoritativeTierProvider = new OffHeapStore.Provider();
OffHeapDiskStore.Provider diskStoreProvider = new OffHeapDiskStore.Provider();
dependencySet.with(cachingTierProvider);
dependencySet.with(authoritativeTierProvider);
dependencySet.with(diskStoreProvider);
dependencySet.with(mock(DiskResourceService.class));
dependencySet.with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS));
ServiceLocator serviceLocator = dependencySet.build();
serviceLocator.startAllServices();
assertThat(serviceLocator.getServicesOfType(CachingTier.Provider.class),
IsCollectionContaining.<CachingTier.Provider>hasItem(IsSame.<CachingTier.Provider>sameInstance(cachingTierProvider)));
assertThat(serviceLocator.getServicesOfType(AuthoritativeTier.Provider.class),
IsCollectionContaining.<AuthoritativeTier.Provider>hasItem(IsSame.<AuthoritativeTier.Provider>sameInstance(authoritativeTierProvider)));
assertThat(serviceLocator.getServicesOfType(OffHeapDiskStore.Provider.class),
IsCollectionContaining.<OffHeapDiskStore.Provider>hasItem(IsSame.<OffHeapDiskStore.Provider>sameInstance(diskStoreProvider)));
}
/**
* @throws java.lang.Exception
*/
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
implRepositoryStore = mock(AbstractConnectorImplRepositoryStore.class);
doAnswer(Answers.CALLS_REAL_METHODS.get()).when(implRepositoryStore)
.cleanJarDependency(any(IRepositoryFileStore.class), any(IRepositoryStore.class), any(IRepositoryStore.class));
connectorImpl = ConnectorImplementationFactory.eINSTANCE.createConnectorImplementation();
connectorImpl.setDefinitionId("def");
connectorImpl.setDefinitionVersion("1.0");
connectorImpl.setImplementationClassname("org.bonita.MyImpl");
connectorImpl.setImplementationId("impl");
connectorImpl.setImplementationVersion("1.0");
JarDependencies deps = ConnectorImplementationFactory.eINSTANCE.createJarDependencies();
String jarName = NamingUtils.toConnectorImplementationFilename(connectorImpl.getImplementationId(), connectorImpl.getImplementationVersion(), false)
+ ".jar";
deps.getJarDependency().add(
jarName);
connectorImpl.setJarDependencies(deps);
doReturn(connectorImpl).when(fStore).getContent();
doReturn(depFileStore).when(dependencyRepositoryStore).getChild(jarName, true);
}
@Test
public void testChannelIsPeriodicallyFlushedToAvoidConsumingTooMuchMemory() {
Channel channel = mock(Channel.class, Answers.RETURNS_DEEP_STUBS);
ResultSetReceiver resultSetReceiver = new ResultSetReceiver(
"select * from t",
channel,
RuntimeException::new,
Collections.singletonList(PGTypes.get(DataTypes.INTEGER)),
null
);
Row1 row1 = new Row1(1);
for (int i = 0; i < 1500; i++) {
resultSetReceiver.setNextRow(row1);
}
verify(channel, times(1)).flush();
}
@Before
public void prepare() {
functions = getFunctions();
memoryManager = new OnHeapMemoryManager(usedBytes -> {});
projectorFactory = new ProjectionToProjectorVisitor(
clusterService,
new NodeJobsCounter(),
functions,
THREAD_POOL,
Settings.EMPTY,
mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS),
new InputFactory(functions),
new EvaluatingNormalizer(
functions,
RowGranularity.SHARD,
r -> Literal.ofUnchecked(r.valueType(), r.valueType().value("1")),
null),
t -> null,
t -> null,
Version.CURRENT,
new ShardId("dummy", UUID.randomUUID().toString(), 0)
);
}
@Before
public void prepare() {
MockitoAnnotations.initMocks(this);
functions = getFunctions();
visitor = new ProjectionToProjectorVisitor(
clusterService,
new NodeJobsCounter(),
functions,
THREAD_POOL,
Settings.EMPTY,
mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS),
new InputFactory(functions),
EvaluatingNormalizer.functionOnlyNormalizer(functions),
t -> null,
t -> null
);
memoryManager = new OnHeapMemoryManager(usedBytes -> {});
avgSignature = Signature.aggregate(
"avg",
DataTypes.INTEGER.getTypeSignature(),
DataTypes.DOUBLE.getTypeSignature()
);
}
@Before
public void prepare() throws Exception {
Functions functions = getFunctions();
memoryManager = new OnHeapMemoryManager(bytes -> {});
projectorFactory = new ProjectionToProjectorVisitor(
clusterService,
new NodeJobsCounter(),
functions,
THREAD_POOL,
Settings.EMPTY,
mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS),
new InputFactory(functions),
new EvaluatingNormalizer(
functions,
RowGranularity.SHARD,
r -> Literal.ofUnchecked(r.valueType(), r.valueType().value("1")),
null),
t -> null,
t -> null,
Version.CURRENT,
new ShardId("dummy", UUID.randomUUID().toString(), 0)
);
}
@Before
public void init() throws Exception {
executorService = mock(ScheduledExecutorService.class, Answers.RETURNS_MOCKS);
jobsLogs = new JobsLogs(() -> true);
sqlOperations = mock(SQLOperations.class, Answers.RETURNS_MOCKS);
decommissioningService = new TestableDecommissioningService(
Settings.EMPTY,
clusterService,
jobsLogs,
executorService,
sqlOperations,
() -> exited.set(true),
mock(TransportClusterHealthAction.class),
mock(TransportClusterUpdateSettingsAction.class)
);
}
@Test
public void test_closing_a_statement_closes_related_portals() {
SQLExecutor sqlExecutor = SQLExecutor.builder(clusterService).build();
DependencyCarrier executor = mock(DependencyCarrier.class, Answers.RETURNS_MOCKS);
Session session = new Session(
sqlExecutor.analyzer,
sqlExecutor.planner,
new JobsLogs(() -> false),
false,
executor,
AccessControl.DISABLED,
SessionContext.systemSessionContext());
session.parse("S_1", "SELECT 1", List.of());
session.bind("P_1", "S_1", List.of(), null);
assertThat(session.portals.size(), is(1));
assertThat(session.preparedStatements.size(), is(1));
session.close((byte) 'S', "S_1");
assertThat(session.portals.entrySet(), Matchers.empty());
assertThat(session.preparedStatements.entrySet(), Matchers.empty());
}
@Test
public void test_discard_all_discards_all_portals_and_prepared_statements() throws Exception {
SQLExecutor sqlExecutor = SQLExecutor.builder(clusterService).build();
DependencyCarrier executor = mock(DependencyCarrier.class, Answers.RETURNS_MOCKS);
Session session = new Session(
sqlExecutor.analyzer,
sqlExecutor.planner,
new JobsLogs(() -> false),
false,
executor,
AccessControl.DISABLED,
SessionContext.systemSessionContext());
session.parse("S_1", "SELECT 1", List.of());
session.bind("P_1", "S_1", List.of(), null);
assertThat(session.portals.size(), is(1));
assertThat(session.preparedStatements.size(), is(1));
session.parse("stmt", "DISCARD ALL", Collections.emptyList());
session.bind("", "stmt", Collections.emptyList(), null);
session.execute("", 0, new BaseResultReceiver());
assertThat(session.portals.entrySet(), Matchers.empty());
assertThat(session.preparedStatements.entrySet(), Matchers.empty());
}
@Test
public void testConstraintViolationException() {
ConstraintViolationException violationException = mock(ConstraintViolationException.class);
ConstraintViolation violation = mock(ConstraintViolation.class, Answers.RETURNS_DEEP_STUBS);
given(violationException.getConstraintViolations()).willReturn(Sets.<ConstraintViolation<?>>newSet(violation));
RpcException rpcException = new RpcException("violation", violationException);
Response response = exceptionMapper.toResponse(rpcException);
assertThat(response, not(nullValue()));
assertThat(response.getEntity(), instanceOf(ViolationReport.class));
}
@Test
public void testWithDatasourceHasNextResult() throws SQLException {
Map<String, DataSource> map = new HashMap<String, DataSource>();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS);
given(dataSource.getConnection()).willReturn(connection);
given(connection.getMetaData().getTypeInfo().next()).willReturn(true);
map.put("mockDatabase", dataSource);
given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())).willReturn(map);
Status status = dataSourceStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.OK));
}
@Test
public void testWithDatasourceNotHasNextResult() throws SQLException {
Map<String, DataSource> map = new HashMap<String, DataSource>();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS);
given(dataSource.getConnection()).willReturn(connection);
given(connection.getMetaData().getTypeInfo().next()).willReturn(false);
map.put("mockDatabase", dataSource);
given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())).willReturn(map);
Status status = dataSourceStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.ERROR));
}
@Before
public void setUp() {
this.generationContext = Mockito.mock(SchemaGenerationContext.class, Answers.RETURNS_DEEP_STUBS);
ObjectMapper objectMapper = new ObjectMapper();
Mockito.when(this.generationContext.getTypeContext()).thenReturn(this.typeContext);
Mockito.when(this.generationContext.getGeneratorConfig().getObjectMapper()).thenReturn(objectMapper);
Mockito.when(this.generationContext.getGeneratorConfig().createObjectNode())
.thenAnswer((_invocation) -> objectMapper.createObjectNode());
Mockito.when(this.generationContext.getKeyword(Mockito.any()))
.thenAnswer(invocation -> ((SchemaKeyword) invocation.getArgument(0)).forVersion(SchemaVersion.DRAFT_2019_09));
}
@Test
void validateAAGUID(@Mock(answer = Answers.RETURNS_DEEP_STUBS) AuthenticatorData<RegistrationExtensionAuthenticatorOutput<?>> authenticatorData) {
AttestationValidator attestationValidator = new AttestationValidator(
Collections.singletonList(new FIDOU2FAttestationStatementValidator()),
new NullCertPathTrustworthinessValidator(),
new NullSelfAttestationTrustworthinessValidator());
AttestationObject attestationObject = mock(AttestationObject.class);
when(attestationObject.getFormat()).thenReturn(FIDOU2FAttestationStatement.FORMAT);
when(authenticatorData.getAttestedCredentialData().getAaguid()).thenReturn(new AAGUID("fea37a71-08ce-479f-bf4b-472a93e2d17d"));
when(attestationObject.getAuthenticatorData()).thenReturn(authenticatorData);
assertThrows(BadAaguidException.class,
() -> attestationValidator.validateAAGUID(attestationObject)
);
}
private OperationService getOperationServiceMock() throws SLException {
OperationService operationServiceMock = mock(OperationService.class);
OperationQuery operationQueryMock = mock(OperationQuery.class, Answers.RETURNS_SELF);
when(operationServiceMock.createQuery()).thenReturn(operationQueryMock);
Mockito.doReturn(getOperation())
.when(operationQueryMock)
.singleResult();
return operationServiceMock;
}
@Test
public void shouldValidateAssertionSubject() {
Subject subject = mock(Subject.class, Answers.RETURNS_DEEP_STUBS);
when(assertion.getSubject()).thenReturn(subject);
when(subject.getNameID().getValue()).thenReturn("any-value");
validator.validate(assertion, "some-expected-in-response-to", "any-entity-id");
verify(subjectValidator).validate(subject, "some-expected-in-response-to");
}
/**
* Setup a {@link MockDataProviderStubber} which can be used to set an expectation to return
* records or throw an exception when the {@code query} is executed on the {@code provider}.
*/
public static MockDataProviderStubber whenQueried(CurioMockDataProvider provider, String query) {
if (mockingDetails(provider).getMockCreationSettings().getDefaultAnswer()
!= Answers.CALLS_REAL_METHODS) {
throw new IllegalStateException(
"CurioMockDataProvider must be initialized with "
+ "@Mock(answer = Answers.CALL_REAL_METHODS).");
}
return new MockDataProviderStubber(provider, query);
}
@Test
public void testMntrBugZk36Solr14463() {
assumeWorkingMockito();
ZookeeperStatusHandler zkStatusHandler = mock(ZookeeperStatusHandler.class);
when(zkStatusHandler.getZkRawResponse("zoo1:2181", "ruok")).thenReturn(Arrays.asList("imok"));
when(zkStatusHandler.getZkRawResponse("zoo1:2181", "mntr")).thenReturn(
Arrays.asList("zk_version\t3.5.5-390fe37ea45dee01bf87dc1c042b5e3dcce88653, built on 05/03/2019 12:07 GMT",
"zk_avg_latency\t1",
"zk_server_state\tleader",
"zk_synced_followers\t2"));
when(zkStatusHandler.getZkRawResponse("zoo1:2181", "conf")).thenReturn(
Arrays.asList("clientPort=2181"));
when(zkStatusHandler.getZkStatus(anyString(), any())).thenCallRealMethod();
when(zkStatusHandler.monitorZookeeper(anyString())).thenCallRealMethod();
when(zkStatusHandler.validateZkRawResponse(ArgumentMatchers.any(), any(), any())).thenAnswer(Answers.CALLS_REAL_METHODS);
Map<String, Object> mockStatus = zkStatusHandler.getZkStatus("zoo1:2181", ZkDynamicConfig.fromZkConnectString("zoo1:2181"));
String expected = "{\n" +
" \"mode\":\"ensemble\",\n" +
" \"dynamicReconfig\":true,\n" +
" \"ensembleSize\":1,\n" +
" \"details\":[{\n" +
" \"zk_synced_followers\":\"2\",\n" +
" \"zk_version\":\"3.5.5-390fe37ea45dee01bf87dc1c042b5e3dcce88653, built on 05/03/2019 12:07 GMT\",\n" +
" \"zk_avg_latency\":\"1\",\n" +
" \"host\":\"zoo1:2181\",\n" +
" \"clientPort\":\"2181\",\n" +
" \"ok\":true,\n" +
" \"zk_server_state\":\"leader\"}],\n" +
" \"zkHost\":\"zoo1:2181\",\n" +
" \"errors\":[\"Leader reports 2 followers, but we only found 0. Please check zkHost configuration\"],\n" +
" \"status\":\"red\"}";
assertEquals(expected, JSONUtil.toJSON(mockStatus));
}
@BeforeEach
void setUp() {
kc = mock(DefaultKubernetesClient.class, Answers.RETURNS_DEEP_STUBS);
configMaps = mock(MixedOperation.class, Answers.RETURNS_DEEP_STUBS);
doneableConfigMap = mock(DoneableConfigMap.class, Answers.RETURNS_DEEP_STUBS);
metadata = mock(DoneableConfigMap.MetadataNested.class, Answers.RETURNS_DEEP_STUBS);
when(kc.inNamespace(anyString()).configMaps()).thenReturn(configMaps);
when(configMaps.withName(anyString()).createNew()).thenReturn(doneableConfigMap);
when(doneableConfigMap.editOrNewMetadata()).thenReturn(metadata);
}
@BeforeEach
void setUp() {
kc = mock(DefaultKubernetesClient.class, Answers.RETURNS_DEEP_STUBS);
leases = mock(MixedOperation.class, Answers.RETURNS_DEEP_STUBS);
doneableLease = mock(DoneableLease.class, Answers.RETURNS_DEEP_STUBS);
metadata = mock(DoneableLease.MetadataNested.class, Answers.RETURNS_DEEP_STUBS);
spec = mock(DoneableLease.SpecNested.class, Answers.RETURNS_DEEP_STUBS);
when(kc.inNamespace(anyString()).leases()).thenReturn(leases);
when(leases.withName(anyString()).createNew()).thenReturn(doneableLease);
when(doneableLease.withNewMetadata()).thenReturn(metadata);
when(doneableLease.withNewSpec()).thenReturn(spec);
}
@Test
void isLeaderAndIsLeaderShouldReturnTrue() {
// Given
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class, Answers.RETURNS_DEEP_STUBS);
when(lec.getLock().identity()).thenReturn("1337");
final LeaderElectionRecord ler = mock(LeaderElectionRecord.class);
when(ler.getHolderIdentity()).thenReturn("1337");
// When
final boolean result = new LeaderElector<>(mock(DefaultKubernetesClient.class), lec).isLeader(ler);
// Then
assertTrue(result);
}
@Test
void isLeaderAndIsNotLeaderShouldReturnFalse() {
// Given
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class, Answers.RETURNS_DEEP_STUBS);
when(lec.getLock().identity()).thenReturn("313373");
final LeaderElectionRecord ler = mock(LeaderElectionRecord.class);
when(ler.getHolderIdentity()).thenReturn("1337");
// When
final boolean result = new LeaderElector<>(mock(DefaultKubernetesClient.class), lec).isLeader(ler);
// Then
assertFalse(result);
}