Java 类org.mockito.ArgumentMatchers 实例源码

项目:plugin-id    文件:UserOrgResourceTest.java   
@Test
public void findAllNotSecure() {
    final Map<String, UserOrg> users = new HashMap<>();
    final UserOrg user1 = newUser();
    users.put("wuser", user1);
    final UserOrg user2 = new UserOrg();
    user2.setCompany("ing");
    user2.setGroups(Collections.singletonList("any"));
    users.put("user2", user2);
    final GroupOrg groupOrg1 = new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", Collections.singleton("wuser"));
    final Map<String, GroupOrg> groupsMap = new HashMap<>();
    groupsMap.put("dig", groupOrg1);
    resource.groupResource = Mockito.mock(GroupResource.class);
    final CompanyOrg company = new CompanyOrg("ou=ing,ou=france,ou=people,dc=sample,dc=com", "ing");
    Mockito.when(companyRepository.findByIdExpected(DEFAULT_USER, "ing")).thenReturn(company);
    groupFindById(DEFAULT_USER, "dig", groupOrg1);
    Mockito.when(userRepository.findAll(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
            .thenReturn(new PageImpl<>(new ArrayList<>(users.values())));
    Mockito.when(resource.groupResource.getContainers()).thenReturn(new HashSet<>(groupsMap.values()));
    Mockito.when(resource.groupResource.getContainersForWrite()).thenReturn(new HashSet<>(groupsMap.values()));

    final List<UserOrg> data = resource.findAllNotSecure(null, null);

    // Check the users
    checkUser(data.get(0));
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP desynchronization
 */
@Test
public void removeUserSync() {
    final GroupLdapRepository groupRepository = new GroupLdapRepository() {
        @Override
        public GroupOrg findById(final String name) {
            // The group has only the user user we want to remove
            return new GroupOrg("dc=" + name, name, Collections.singleton("flast1"));
        }

    };
    groupRepository.setLdapCacheRepository(Mockito.mock(LdapCacheRepository.class));
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("any"))).when(ldapTemplate)
            .modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());
    removeUser(groupRepository);
}
项目:kotlin-late    文件:LateTest.java   
@Before
public void before() throws Exception {
    Answer<Cancelable> runAndReturn = new Answer<Cancelable>() {
        @Override
        public Cancelable answer(InvocationOnMock invocation) throws Exception {
            try {
                Function0<Unit> block = invocation.getArgument(0);
                block.invoke();
            } catch (Exception e) {
                e.printStackTrace();
                Assert.fail(e.getMessage());
            }
            return canceler;
        }
    };
    doAnswer(runAndReturn).when(mockRunner).runWithCancel(ArgumentMatchers.<Function0<Unit>>any());
    doAnswer(runAndReturn).when(mockRunner).run(ArgumentMatchers.<Function0<Unit>>any());
}
项目:plugin-prov-aws    文件:ProvAwsPluginResourceTest.java   
/**
 * retrieve keys from AWS
 * 
 * @throws Exception
 *             exception
 */
@Test
public void getEC2Keys() throws Exception {
    final ProvAwsPluginResource resource = Mockito.spy(this.resource);
    final CurlRequest mockRequest = new CurlRequest("GET", MOCK_URL, null);
    mockRequest.setSaveResponse(true);
    Mockito.doReturn(mockRequest).when(resource).newRequest(ArgumentMatchers.any(AWS4SignatureQueryBuilder.class),
            ArgumentMatchers.eq(subscription));
    httpServer.stubFor(
            get(urlEqualTo("/mock")).willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody("<keyName>my-key</keyName>")));
    httpServer.start();

    final List<NamedBean<String>> keys = resource.getEC2Keys(subscription);
    Assert.assertFalse(keys.isEmpty());
    Assert.assertEquals(1, keys.size());
    Assert.assertEquals("my-key", keys.get(0).getId());
}
项目:plugin-id    文件:UserOrgResourceTest.java   
@Test
public void findAllNotSecureByManagedGroup() {
    final Map<String, UserOrg> users = new HashMap<>();
    final UserOrg user1 = newUser();
    users.put("wuser", user1);
    final UserOrg user2 = new UserOrg();
    user2.setCompany("ing");
    user2.setGroups(Collections.singletonList("any"));
    users.put("user2", user2);
    final GroupOrg groupOrg1 = new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", Collections.singleton("wuser"));
    final Map<String, GroupOrg> groupsMap = new HashMap<>();
    groupsMap.put("dig", groupOrg1);
    resource.groupResource = Mockito.mock(GroupResource.class);
    final CompanyOrg company = new CompanyOrg("ou=ing,ou=france,ou=people,dc=sample,dc=com", "ing");
    Mockito.when(companyRepository.findByIdExpected(DEFAULT_USER, "ing")).thenReturn(company);
    groupFindById(DEFAULT_USER, "dig", groupOrg1);
    Mockito.when(userRepository.findAll(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
            .thenReturn(new PageImpl<>(new ArrayList<>(users.values())));
    Mockito.when(resource.groupResource.getContainers()).thenReturn(new HashSet<>(groupsMap.values()));
    Mockito.when(resource.groupResource.getContainersForWrite()).thenReturn(new HashSet<>(groupsMap.values()));

    final List<UserOrg> data = resource.findAllNotSecure(null, "dig");

    // Check the users
    checkUser(data.get(0));
}
项目:NoRiskNoFun    文件:ClientConnectedStateTests.java   
@Test
public void handleOutboundMessageTerminatesClientIfErrorOccursDuringSend() {

    // given
    ClientConnectedState target = new ClientConnectedState(client);
    doThrow(IOException.class).when(mockSession).write(ArgumentMatchers.any(byte[].class));

    // when
    target.handleOutboundMessage(new SerializableMessage());

    // then
    assertThat(messageQueue.size(), is(1));
    assertThat(messageQueue.get(0), is(instanceOf(ClientDisconnected.class)));
    assertThat(client.getCurrentState(), is(instanceOf(ClientDisconnectedState.class)));
    verify(mockSession, times(1)).write(ArgumentMatchers.any(byte[].class));
    verify(mockSession, times(1)).terminate();
    verifyNoMoreInteractions(mockSession);
}
项目:plugin-bt-jira    文件:JiraImportPluginResourceTest.java   
@Test
public void testSynchronizeJira() throws Exception {
    final ImportContext context = new ImportContext();
    final ImportStatus result = new ImportStatus();
    result.setCanSynchronizeJira(true);
    final JiraImportPluginResource resource = Mockito.mock(JiraImportPluginResource.class);
    Mockito.doCallRealMethod().when(resource).synchronizeJira(ArgumentMatchers.same(context), ArgumentMatchers.same(result));
    Mockito.when(resource.authenticateAdmin(ArgumentMatchers.same(context), ArgumentMatchers.any(CurlProcessor.class)))
            .thenReturn(true);
    Mockito.when(resource.clearJiraCache(ArgumentMatchers.same(context), ArgumentMatchers.same(result),
            ArgumentMatchers.any(CurlProcessor.class))).thenReturn(true);
    Mockito.when(resource.reIndexProject(ArgumentMatchers.same(context), ArgumentMatchers.same(result),
            ArgumentMatchers.any(CurlProcessor.class))).thenReturn(true);
    resource.synchronizeJira(context, result);
    Assert.assertTrue(result.getSynchronizedJira());
}
项目:NoRiskNoFun    文件:ClientHandshakeStateTests.java   
@Test
public void whenSendingHandshakeMessageFailsClientIsTerminated() {

    // given
    doThrow(IOException.class).when(mockSession).write(ArgumentMatchers.any(byte[].class));

    ClientHandshakeState target = new ClientHandshakeState(client);

    // when
    client.setState(target);

    // then
    assertThat(client.getCurrentState(), is(instanceOf(ClientDisconnectedState.class)));
    assertThat(messageQueue.size(), is(2));
    assertThat(messageQueue.get(0), is(instanceOf(ClientConnectionRefused.class)));
    assertThat(((ClientConnectionRefused)messageQueue.get(0)).getReason(), Matchers.startsWith("Failed to send handshake: "));

    verify(mockSession, times(1)).write(ArgumentMatchers.any(byte[].class));
    verify(mockSession, times(1)).terminate();
    verifyNoMoreInteractions(mockSession);
}
项目:NoRiskNoFun    文件:ClientHandshakeStateTests.java   
@Test
public void handleSessionClosedMakesStateTransition() {

    // given
    doThrow(IOException.class).when(mockSession).write(ArgumentMatchers.any(byte[].class));

    ClientHandshakeState target = new ClientHandshakeState(client);

    // when
    target.handleSessionClosed(mockSession);

    // then
    assertThat(client.getCurrentState(), is(instanceOf(ClientDisconnectedState.class)));
    assertThat(messageQueue.size(), is(2));
    assertThat(messageQueue.get(0), is(instanceOf(ClientConnectionRefused.class)));
    assertThat(((ClientConnectionRefused)messageQueue.get(0)).getReason(), is("connection closed by server"));

    verifyZeroInteractions(mockSession);
}
项目:NoRiskNoFun    文件:ClientConnectedStateTests.java   
@Test
public void processDataReceivedTerminatesSendingMessageToClientFails() throws IOException, ProtocolException {

    // given
    doThrow(IOException.class).when(sessionMock).write(ArgumentMatchers.any(byte[].class));

    Handshake handshake = new Handshake(HandshakeConstants.HANDSHAKE_MAGIC, HandshakeConstants.HANDSHAKE_PROTOCOL_VERSION);
    byte[] handshakeData = new MessageSerializer(handshake).serialize();

    client.processDataReceived(handshakeData);
    ClientConnectedState target = new ClientConnectedState(client);

    // when
    target.processDataReceived();

    // then
    assertThat(client.getCurrentState(), is(instanceOf(ClientClosedState.class)));
    verify(sessionMock, times(1)).terminate();
    verify(sessionMock, times(1)).write(ArgumentMatchers.any(byte[].class));
    verifyNoMoreInteractions(sessionMock);
    verifyNoMoreInteractions(messageBusMock);
}
项目:NoRiskNoFun    文件:NetworkClientTests.java   
@Test
public void connectWhenRegisteringClientSocketThrowsException() throws IOException {

    // given
    when(socketFactoryMock.openSocketSelector()).thenReturn(selectorMock);
    when(socketFactoryMock.openClientSocket(anyString(), anyInt())).thenReturn(socketMock);
    doThrow(IOException.class).when(selectorMock).register(ArgumentMatchers.any(TCPClientSocket.class), anyBoolean());

    // when
    boolean obtained = client.connect(HOST, PORT);

    // then
    assertThat(obtained, is(false));
    assertThat(client.isRunning(), is(false));

    // verify method calls
    verify(socketFactoryMock, times(1)).openSocketSelector();
    verify(socketFactoryMock, times(1)).openClientSocket(anyString(), anyInt());
    verify(selectorMock, times(1)).register(any(TCPClientSocket.class), anyBoolean());
    verify(selectorMock, times(1)).close();
    verify(socketMock, times(1)).close();
}
项目:NoRiskNoFun    文件:NetworkClientTests.java   
@Test
public void closingSocketAndSelectorWhenExceptionIsThrownInClose() throws IOException {

    // given
    when(socketFactoryMock.openSocketSelector()).thenReturn(selectorMock);
    when(socketFactoryMock.openClientSocket(anyString(), anyInt())).thenReturn(socketMock);
    doThrow(IOException.class).when(selectorMock).register(ArgumentMatchers.any(TCPClientSocket.class), anyBoolean());
    doThrow(IOException.class).when(selectorMock).close();
    doThrow(IOException.class).when(socketMock).close();

    // when
    boolean obtained = client.connect(HOST, PORT);

    // then
    assertThat(obtained, is(false));
    assertThat(client.isRunning(), is(false));

    // verify method calls
    verify(socketFactoryMock, times(1)).openSocketSelector();
    verify(socketFactoryMock, times(1)).openClientSocket(anyString(), anyInt());
    verify(selectorMock, times(1)).register(any(TCPClientSocket.class), anyBoolean());
    verify(selectorMock, times(1)).close();
    verify(socketMock, times(1)).close();
}
项目:plugin-id    文件:UserBatchLdapResourceTest.java   
@SuppressWarnings("unchecked")
@Before
public void mockApplicationContext() {
    final ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
    SpringUtils.setSharedApplicationContext(applicationContext);
    mockLdapResource = Mockito.mock(UserOrgResource.class);
    final UserFullLdapTask mockTask = new UserFullLdapTask();
    mockTask.resource = mockLdapResource;
    mockTask.securityHelper = securityHelper;
    final UserAtomicLdapTask mockTaskUpdate = new UserAtomicLdapTask();
    mockTaskUpdate.resource = mockLdapResource;
    mockTaskUpdate.securityHelper = securityHelper;
    Mockito.when(applicationContext.getBean(SessionSettings.class)).thenReturn(new SessionSettings());
    Mockito.when(applicationContext.getBean((Class<?>) ArgumentMatchers.any(Class.class))).thenAnswer((Answer<Object>) invocation -> {
        final Class<?> requiredType = (Class<Object>) invocation.getArguments()[0];
        if (requiredType == UserFullLdapTask.class) {
            return mockTask;
        }
        if (requiredType == UserAtomicLdapTask.class) {
            return mockTaskUpdate;
        }
        return UserBatchLdapResourceTest.super.applicationContext.getBean(requiredType);
    });

    mockTaskUpdate.jaxrsFactory = ServerProviderFactory.createInstance(null);
}
项目:NoRiskNoFun    文件:SessionImplTests.java   
@Test
public void aClosedSessionDoesNotStoreReadDataFromSocket() throws IOException {

    // given
    final String message = "Hello World!";

    when(socketMock.read(ArgumentMatchers.any(ByteBuffer.class))).then(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            ByteBuffer data = invocation.getArgument(0);
            data.put(message.getBytes());

            return message.getBytes().length;
        }
    });
    SessionImpl target = new SessionImpl(selectorMock);
    target.close();

    // when
    int obtained = target.doReadFromSocket(socketMock);

    // then
    assertThat(obtained, is(0));
    assertThat(target.read(), is(nullValue()));
}
项目:bootstrap    文件:TAbstractRepeatableSeleniumTest.java   
@SuppressWarnings("unchecked")
@Override
protected void prepareDriver() throws Exception {
    System.clearProperty("test.selenium.remote");
    localDriverClass = WebDriverMock.class.getName();
    remoteDriverClass = WebDriverMock.class.getName();
    scenario = "sc";
    super.prepareDriver();
    mockDriver = Mockito.mock(WebDriverMock.class);
    Mockito.when(mockDriver.getScreenshotAs(ArgumentMatchers.any(OutputType.class))).thenReturn(
            new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI()));
    final Options options = Mockito.mock(Options.class);
    Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class));
    Mockito.when(mockDriver.manage()).thenReturn(options);
    final WebElement webElement = Mockito.mock(WebElement.class);
    Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement);
    Mockito.when(webElement.isDisplayed()).thenReturn(true);
    this.driver = mockDriver;
}
项目:bootstrap    文件:JpaBenchResourceTest.java   
@Test(expected = IllegalStateException.class)
public void testDownloadDataBlobError() throws Exception {
    final URL jarLocation = getBlobFile();
    InputStream openStream = null;
    try {
        // Get the JAR input
        openStream = jarLocation.openStream();

        // Proceed to the test
        resource.prepareData(openStream, 1);
        final StreamingOutput downloadLobFile = resource.downloadLobFile();
        final OutputStream output = Mockito.mock(OutputStream.class);
        Mockito.doThrow(new IOException()).when(output).write(ArgumentMatchers.any(byte[].class));

        downloadLobFile.write(output);
    } finally {
        IOUtils.closeQuietly(openStream);
    }
}
项目:endpoint-health    文件:EndPointServiceTest.java   
@Before
public void setUp() {
    endPointService = new EndPointServiceImpl(endPointDao, endPointCheckSchedulerService, lockService);

    Mockito.doAnswer(invocation -> {
        ((Runnable) invocation.getArguments()[1]).run();
        return null;
    }).when(lockService).doInLock(ArgumentMatchers.any(), ArgumentMatchers.any());

    Mockito.when(endPointDao.find(EXISTING_ID)).thenReturn(Optional.of(existingEndPoint));
    Mockito.when(endPointDao.findByName(EXISTING_NAME)).thenReturn(Optional.of(existingEndPoint));

    endPoints = Arrays.asList(existingEndPoint, otherExistingEndPoint);

    Mockito.when(endPointDao.findAll()).thenReturn(endPoints);
}
项目:endpoint-health    文件:EndPointCheckServiceTest.java   
@Before
public void setUp() throws ParseException {
    existingEndPoint = new EndPoint();

    endPointCheckService = new EndPointCheckServiceImpl(endPointCheckDao, endPointCheckerFactory, endPointService);

    Mockito.when(endPointService.findEndPoint(EXISTING_END_POINT_ID)).thenReturn(existingEndPoint);

    Mockito.when(endPointCheckerFactory.createEndPointChecker(ArgumentMatchers.any()))
            .thenReturn(endPointChecker);

    startDate = new SimpleDateFormat(EndPointCheckResourceImpl.DATE_FORMAT).parse("2017-01-01");
    endDate = new SimpleDateFormat(EndPointCheckResourceImpl.DATE_FORMAT).parse("2017-01-02");

    Mockito.when(endPointCheckDao
            .findByDateRange(ArgumentMatchers.eq(existingEndPoint),
                ArgumentMatchers.eq(Utils.toStartOfDay(startDate)),
                ArgumentMatchers.eq(Utils.toEndOfDay(endDate))))
            .thenReturn(endPointChecks);
}
项目:plugin-bt-jira    文件:JiraImportPluginResourceTest.java   
@Test
public void testSynchronizeJiraNoScriptRunner() throws Exception {
    final ImportContext context = new ImportContext();
    final ImportStatus result = new ImportStatus();
    result.setCanSynchronizeJira(true);
    final JiraImportPluginResource resource = Mockito.mock(JiraImportPluginResource.class);
    Mockito.doCallRealMethod().when(resource).synchronizeJira(ArgumentMatchers.same(context), ArgumentMatchers.same(result));
    Mockito.when(resource.authenticateAdmin(ArgumentMatchers.same(context), ArgumentMatchers.any(CurlProcessor.class)))
            .thenReturn(true);
    resource.synchronizeJira(context, result);
    Mockito.verify(resource, Mockito.times(1)).authenticateAdmin(ArgumentMatchers.same(context),
            ArgumentMatchers.any(CurlProcessor.class));
    Mockito.verify(resource, Mockito.times(1)).clearJiraCache(ArgumentMatchers.same(context), ArgumentMatchers.same(result),
            ArgumentMatchers.any(CurlProcessor.class));
    Mockito.verify(resource, Mockito.never()).reIndexProject(ArgumentMatchers.same(context), ArgumentMatchers.same(result),
            ArgumentMatchers.any(CurlProcessor.class));
    Assert.assertFalse(result.getSynchronizedJira());
}
项目:plugin-id    文件:GroupBatchLdapResourceTest.java   
@SuppressWarnings("unchecked")
@Before
public void mockApplicationContext() {
    final ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
    SpringUtils.setSharedApplicationContext(applicationContext);
    mockLdapResource = Mockito.mock(GroupResource.class);
    final GroupFullLdapTask mockTask = new GroupFullLdapTask();
    mockTask.resource = mockLdapResource;
    mockTask.securityHelper = securityHelper;
    mockTask.containerScopeResource = Mockito.mock(ContainerScopeResource.class);
    Mockito.when(applicationContext.getBean(SessionSettings.class)).thenReturn(new SessionSettings());
    Mockito.when(applicationContext.getBean((Class<?>) ArgumentMatchers.any(Class.class))).thenAnswer((Answer<Object>) invocation -> {
        final Class<?> requiredType = (Class<Object>) invocation.getArguments()[0];
        if (requiredType == GroupFullLdapTask.class) {
            return mockTask;
        }
        return GroupBatchLdapResourceTest.super.applicationContext.getBean(requiredType);
    });

    final ContainerScope container = new ContainerScope();
    container.setId(1);
    container.setName("Fonction");
    container.setType(ContainerType.GROUP);
    Mockito.when(mockTask.containerScopeResource.findByName("Fonction")).thenReturn(container);
}
项目:plugin-id    文件:UserOrgResourceTest.java   
@Test
public void findAllNotSecureByManagedCompany() {
    final Map<String, UserOrg> users = new HashMap<>();
    final UserOrg user1 = newUser();
    users.put("wuser", user1);
    final UserOrg user2 = new UserOrg();
    user2.setCompany("ing");
    user2.setGroups(Collections.singletonList("any"));
    users.put("user2", user2);
    final GroupOrg groupOrg1 = new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", Collections.singleton("wuser"));
    final Map<String, GroupOrg> groupsMap = new HashMap<>();
    groupsMap.put("dig", groupOrg1);
    resource.companyResource = Mockito.mock(CompanyResource.class);
    final CompanyOrg company = new CompanyOrg("ou=ing,ou=france,ou=people,dc=sample,dc=com", "ing");
    Mockito.when(companyRepository.findByIdExpected(DEFAULT_USER, "ing")).thenReturn(company);
    groupFindById(DEFAULT_USER, "dig", groupOrg1);
    Mockito.when(userRepository.findAll(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
            .thenReturn(new PageImpl<>(new ArrayList<>(users.values())));
    Mockito.when(resource.companyResource.getContainers()).thenReturn(Collections.singleton(company));
    Mockito.when(resource.companyResource.getContainersForWrite()).thenReturn(Collections.singleton(company));

    final List<UserOrg> data = resource.findAllNotSecure("ing", null);

    // Check the users
    checkUser(data.get(0));
}
项目:server    文件:BlockSyncTestIT.java   
@Test
public void step_2_two_block() throws Exception {

    Block lastBlock = ctx1.context.getInstance().getBlockchainService().getLastBlock();

    Mockito.when(mockTimeProvider.get()).thenReturn(lastBlock.getTimestamp() + 180 * 2 + 1);

    ctx1.generateBlockForNow();
    ctx2.fullBlockSync();

    Mockito.verify(ctx1.syncBlockPeerService, Mockito.times(1)).getLastBlock();
    Mockito.verify(ctx1.syncBlockPeerService, Mockito.times(1)).getBlockHistory(ArgumentMatchers.any());

    Assert.assertEquals("Blockchain synchronized",
            ctx1.context.getInstance().getBlockchainService().getLastBlock().getID(),
            ctx2.context.getInstance().getBlockchainService().getLastBlock().getID());
}
项目:server    文件:BlockSyncTestIT.java   
@Test
public void step_5_too_many_blocks() throws Exception {

    Block lastBlock = ctx1.context.getInstance().getBlockchainService().getLastBlock();

    int time = lastBlock.getTimestamp() + Constant.BLOCK_PERIOD * Constant.BLOCK_IN_DAY * 2 + 1;
    Mockito.when(mockTimeProvider.get()).thenReturn(time);

    ctx1.generateBlockForNow();

    ctx2.syncBlockListTask.run();

    Mockito.verify(ctx1.syncBlockPeerService, Mockito.times(1)).getLastBlock();
    Mockito.verify(ctx1.syncBlockPeerService, Mockito.atLeast(2)).getBlockHistory(ArgumentMatchers.any());
    Mockito.verify(ctx1.syncBlockPeerService, Mockito.atLeast(2)).getDifficulty();

    Assert.assertEquals("Blockchain synchronized",
            ctx1.context.getInstance().getBlockchainService().getLastBlock().getID(),
            ctx2.context.getInstance().getBlockchainService().getLastBlock().getID());
}
项目:rufus    文件:FeedProcessorImplTest.java   
@Test
public void testUserSubscriptions() throws MalformedURLException {
    ArticleDao articleDao = Mockito.mock(ArticleDao.class);
    Mockito.when(articleDao.hasSubscriptions(ArgumentMatchers.anyLong())).thenReturn(true);
    Mockito.when(articleDao.getSources(ArgumentMatchers.anyLong())).thenReturn(Collections.singletonList(new Source(new URL(NYTIMES))));
    FeedProcessor processor = FeedProcessorImpl.newInstance(articleDao);
    List<Article> articles = processor.buildArticleCollection(Mockito.mock(User.class));

    assertTrue(!articles.isEmpty());
    assertThat(
        "Every articles has a description",
        articles,
        everyItem(
            hasProperty("description", not(blankOrNullString()))
        )
    );
}
项目:bootstrap    文件:TAbstractParallelSeleniumTest.java   
@SuppressWarnings("unchecked")
@Override
protected void prepareDriver() throws Exception {
    testName = Mockito.mock(TestName.class);
    Mockito.when(testName.getMethodName()).thenReturn("mockTest");
    System.clearProperty("test.selenium.remote");
    localDriverClass = WebDriverMock.class.getName();
    remoteDriverClass = WebDriverMock.class.getName();
    scenario = "sc";
    super.prepareDriver();
    mockDriver = Mockito.mock(WebDriverMock.class);
    Mockito.when(((WebDriverMock) mockDriver).getScreenshotAs(ArgumentMatchers.any(OutputType.class))).thenReturn(
            new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI()));
    final Options options = Mockito.mock(Options.class);
    Mockito.when(options.window()).thenReturn(Mockito.mock(Window.class));
    Mockito.when(mockDriver.manage()).thenReturn(options);
    final WebElement webElement = Mockito.mock(WebElement.class);
    Mockito.when(mockDriver.findElement(ArgumentMatchers.any(By.class))).thenReturn(webElement);
    Mockito.when(webElement.isDisplayed()).thenReturn(true);
    this.driver = mockDriver;
}
项目:plugin-id    文件:UserOrgResourceTest.java   
@Test
public void findAllNotSecureByGroup() {
    final Map<String, UserOrg> users = new HashMap<>();
    final UserOrg user1 = newUser();
    users.put("wuser", user1);
    final UserOrg user2 = new UserOrg();
    user2.setCompany("ing");
    user2.setGroups(Collections.singletonList("any"));
    users.put("user2", user2);
    final GroupOrg groupOrg1 = new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", Collections.singleton("wuser"));
    final Map<String, GroupOrg> groupsMap = new HashMap<>();
    groupsMap.put("dig", groupOrg1);
    resource.groupResource = Mockito.mock(GroupResource.class);
    final CompanyOrg company = new CompanyOrg("ou=ing,ou=france,ou=people,dc=sample,dc=com", "ing");
    Mockito.when(companyRepository.findByIdExpected(DEFAULT_USER, "ing")).thenReturn(company);
    groupFindById(DEFAULT_USER, "dig", groupOrg1);
    Mockito.when(userRepository.findAll(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
            .thenReturn(new PageImpl<>(new ArrayList<>(users.values())));
    Mockito.when(resource.groupResource.getContainers()).thenReturn(new HashSet<>(groupsMap.values()));
    Mockito.when(resource.groupResource.getContainersForWrite()).thenReturn(new HashSet<>(groupsMap.values()));

    final List<UserOrg> data = resource.findAllNotSecure(null, "dig");

    // Check the users
    checkUser(data.get(0));
}
项目:plugin-bt-jira    文件:JiraImportPluginResourceTest.java   
@Test
public void testSynchronizeJiraReindexFailed() throws Exception {
    final ImportContext context = new ImportContext();
    final ImportStatus result = new ImportStatus();
    result.setCanSynchronizeJira(true);
    final JiraImportPluginResource resource = Mockito.mock(JiraImportPluginResource.class);
    Mockito.doCallRealMethod().when(resource).synchronizeJira(ArgumentMatchers.same(context), ArgumentMatchers.same(result));
    Mockito.when(resource.authenticateAdmin(ArgumentMatchers.same(context), ArgumentMatchers.any(CurlProcessor.class)))
            .thenReturn(true);
    Mockito.when(resource.clearJiraCache(ArgumentMatchers.same(context), ArgumentMatchers.same(result),
            ArgumentMatchers.any(CurlProcessor.class))).thenReturn(true);
    resource.synchronizeJira(context, result);
    Mockito.verify(resource, Mockito.times(1)).authenticateAdmin(ArgumentMatchers.same(context),
            ArgumentMatchers.any(CurlProcessor.class));
    Mockito.verify(resource, Mockito.times(1)).clearJiraCache(ArgumentMatchers.same(context), ArgumentMatchers.same(result),
            ArgumentMatchers.any(CurlProcessor.class));
    Mockito.verify(resource, Mockito.times(1)).reIndexProject(ArgumentMatchers.same(context), ArgumentMatchers.same(result),
            ArgumentMatchers.any(CurlProcessor.class));
    Assert.assertFalse(result.getSynchronizedJira());
}
项目:plugin-bt-jira    文件:JiraImportPluginResourceTest.java   
@Test
public void testSynchronizeJiraCantSynchronize() throws Exception {
    final ImportContext context = new ImportContext();
    final ImportStatus result = new ImportStatus();
    result.setCanSynchronizeJira(false);
    final JiraImportPluginResource resource = Mockito.mock(JiraImportPluginResource.class);
    Mockito.doCallRealMethod().when(resource).synchronizeJira(ArgumentMatchers.same(context), ArgumentMatchers.same(result));
    resource.synchronizeJira(context, result);
    Mockito.verify(resource, Mockito.never()).authenticateAdmin(ArgumentMatchers.same(context),
            ArgumentMatchers.any(CurlProcessor.class));
    Assert.assertNull(result.getSynchronizedJira());
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a not managed LDAP desynchronization
 */
@Test(expected = org.springframework.ldap.AttributeInUseException.class)
public void addUserSyncError() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("any"))).when(ldapTemplate)
            .modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());

    addUser(groupRepository);
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP desynchronization
 */
@Test
public void addUserSync1() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("value #0 already exists")))
            .when(ldapTemplate).modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());

    addUser(groupRepository);
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP desynchronization
 */
@Test
public void addUserSync2() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("ATTRIBUTE_OR_VALUE_EXISTS")))
            .when(ldapTemplate).modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());

    addUser(groupRepository);
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP schema violation
 */
@Test
public void removeUserNotMember() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.SchemaViolationException(new SchemaViolationException("any"))).when(ldapTemplate)
            .modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());
    removeUser(groupRepository);
}
项目:plugin-prov-aws    文件:ProvAwsPluginResourceTest.java   
@Test
public void checkSubscriptionStatusDown() throws Exception {
    final ProvAwsPluginResource resource = Mockito.spy(ProvAwsPluginResource.class);
    Mockito.doReturn(false).when(resource).validateAccess(ArgumentMatchers.anyInt());
    final SubscriptionStatusWithData status = resource.checkSubscriptionStatus(subscription, null, new HashMap<String, String>());
    Assert.assertFalse(status.getStatus().isUp());
}
项目:plugin-id-ldap    文件:UserLdapRepositoryTest.java   
@SuppressWarnings("unchecked")
@Test
public void getTokenNotExists() {
    final LdapTemplate mock = Mockito.mock(LdapTemplate.class);
    Mockito.when(mock.search((String) ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(ContextMapper.class)))
            .thenReturn(Collections.emptyList());
    repository.setTemplate(mock);
    Assert.assertNull(repository.getToken("any"));
}
项目:qpp-conversion-tool    文件:ConversionFileWriterWrapperTest.java   
@Test
@PrepareForTest({Files.class, ConversionFileWriterWrapper.class})
public void testFailureToWriteQpp() throws IOException {
    PowerMockito.mockStatic(Files.class);
    PowerMockito.when(Files.newBufferedWriter(ArgumentMatchers.any(Path.class))).thenThrow(new IOException());

    Path path = Paths.get("../qrda-files/valid-QRDA-III-latest.xml");
    ConversionFileWriterWrapper converterWrapper = new ConversionFileWriterWrapper(path);

    converterWrapper.transform();

    assertFileDoesNotExists("valid-QRDA-III-latest.qpp.json");
}
项目:qpp-conversion-tool    文件:ConversionFileWriterWrapperTest.java   
@Test
@PrepareForTest({Files.class, ConversionFileWriterWrapper.class})
public void testFailureToWriteErrors() throws IOException {
    PowerMockito.mockStatic(Files.class);
    PowerMockito.when(Files.newBufferedWriter(ArgumentMatchers.any(Path.class))).thenThrow(new IOException());

    Path path = Paths.get("src/test/resources/not-a-QRDA-III-file.xml");
    ConversionFileWriterWrapper converterWrapper = new ConversionFileWriterWrapper(path);

    converterWrapper.transform();

    assertFileDoesNotExists("not-a-QRDA-III-file.err.json");
}
项目:plugin-prov-aws    文件:AWS4SignerBaseTest.java   
/**
 * Test method for
 * {@link org.ligoj.app.plugin.prov.aws.auth.AWS4SignerBase#getCanonicalizedQueryString(java.util.Map)}.
 */
@Test(expected = TechnicalException.class)
public void testGetCanonicalizedQueryStringException() throws Exception {
    final AWS4SignerBase signer = new AWS4SignerForAuthorizationHeader();
    final URLCodec urlCodec = Mockito.mock(URLCodec.class);
    ReflectionTestUtils.setField(signer, "urlCodec", urlCodec);
    Mockito.when(urlCodec.encode(ArgumentMatchers.anyString())).thenThrow(new EncoderException());
    signer.getCanonicalizedQueryString(ImmutableMap.of("q2", "v2", "q1", "v1"));
}