java类org.hamcrest.CustomMatcher的实例源码

GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 29 收藏 0 点赞 0 评论 0
@Test
public void testBadRepo() throws Exception
{
  expectedException.expect(new CustomMatcher<Object>(IllegalArgumentException.class.getName())
  {
    @Override
    public boolean matches(Object item)
    {
      return item instanceof IllegalArgumentException;
    }
  });
  new GSWagon()
  {
    public Repository getRepository()
    {
      return new Repository("id", "http://bucket/key");
    }
  }.openConnectionInternal();
}
TransportClientNodesServiceTests.java 文件源码 项目:elasticsearch_my 阅读 32 收藏 0 点赞 0 评论 0
private void checkRemoveAddress(boolean sniff) {
    Object[] extraSettings = {TransportClient.CLIENT_TRANSPORT_SNIFF.getKey(), sniff};
    try(TestIteration iteration = new TestIteration(extraSettings)) {
        final TransportClientNodesService service = iteration.transportClientNodesService;
        assertEquals(iteration.listNodesCount + iteration.sniffNodesCount, service.connectedNodes().size());
        final TransportAddress addressToRemove = randomFrom(iteration.listNodeAddresses);
        service.removeTransportAddress(addressToRemove);
        assertThat(service.connectedNodes(), everyItem(not(new CustomMatcher<DiscoveryNode>("removed address") {
            @Override
            public boolean matches(Object item) {
                return item instanceof DiscoveryNode && ((DiscoveryNode)item).getAddress().equals(addressToRemove);
            }
        })));
        assertEquals(iteration.listNodesCount + iteration.sniffNodesCount - 1, service.connectedNodes().size());
    }
}
ParseMessageDataSourceTest.java 文件源码 项目:Chateau 阅读 33 收藏 0 点赞 0 评论 0
@Test
public void sendTextMessage() {
    // Setup
    ExampleMessage message = ExampleMessage.createOutgoingTextMessage(TEST_CHAT_ID, "Hello world");
    final MessageQueries.SendQuery<ExampleMessage> sendQuery = new MessageQueries.SendQuery<>(TEST_CHAT_ID, message);
    final TestSubscriber<Update<ExampleMessage>> testSubscriber = new TestSubscriber<>();

    // Execute
    mUpdates.subscribe(testSubscriber);
    mTarget.send(sendQuery).subscribe();

    // Assert
    verify(mMockParseHelper).save(argThat(new CustomMatcher<ParseObject>("") {
        @Override
        public boolean matches(Object item) {
            final ParseObject parseMessage = (ParseObject) item;

            return parseMessage.getClassName().equals(MessagesTable.NAME);
        }
    }));
    testSubscriber.assertValueCount(2);
}
MkIssueTest.java 文件源码 项目:typed-github 阅读 26 收藏 0 点赞 0 评论 0
/**
 * MkIssue can list its labels.
 * @throws Exception If some problem inside
 */
@Test
public void listsReadOnlyLabels() throws Exception {
    final Issue issue = this.issue();
    final String tag = "test-tag";
    issue.repo().labels().create(tag, "c0c0c0");
    issue.labels().add(Collections.singletonList(tag));
    MatcherAssert.assertThat(
        new Issue.Smart(issue).roLabels().iterate(),
        Matchers.<Label>hasItem(
            new CustomMatcher<Label>("label just created") {
                @Override
                public boolean matches(final Object item) {
                    return Label.class.cast(item).name().equals(tag);
                }
            }
        )
    );
}
HttpMatchers.java 文件源码 项目:rulz 阅读 31 收藏 0 点赞 0 评论 0
public static Matcher<Response> successful() {
    return new CustomMatcher<Response>("2xx family of successful responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
HttpMatchers.java 文件源码 项目:rulz 阅读 29 收藏 0 点赞 0 评论 0
public static Matcher<Response> clientError() {
       return new CustomMatcher<Response>("4xx (client error) family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.CLIENT_ERROR);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
HttpMatchers.java 文件源码 项目:rulz 阅读 30 收藏 0 点赞 0 评论 0
public static Matcher<Response> redirection() {
    return new CustomMatcher<Response>("3xx (redirection) family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.REDIRECTION);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
HttpMatchers.java 文件源码 项目:rulz 阅读 29 收藏 0 点赞 0 评论 0
public static Matcher<Response> informational() {
    return new CustomMatcher<Response>("1xx (informational) family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.INFORMATIONAL);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }
    };
}
HttpMatchers.java 文件源码 项目:rulz 阅读 27 收藏 0 点赞 0 评论 0
public static Matcher<Response> other() {
    return new CustomMatcher<Response>("unrecognized family of responses") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatusInfo().getFamily() == Response.Status.Family.OTHER);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }
    };
}
HttpMatchers.java 文件源码 项目:rulz 阅读 25 收藏 0 点赞 0 评论 0
public static Matcher<Response> noContent() {
    final int statusCode = Response.Status.NO_CONTENT.getStatusCode();
    return new CustomMatcher<Response>("no content (" + statusCode + ")") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatus() == statusCode);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
HttpMatchers.java 文件源码 项目:rulz 阅读 26 收藏 0 点赞 0 评论 0
public static Matcher<Response> serverError() {
    final int statusCode = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
    return new CustomMatcher<Response>("Internal server error(" + statusCode + ")") {

        @Override
        public boolean matches(Object o) {
            return (o instanceof Response)
                    && (((Response) o).getStatus() == statusCode);
        }

        @Override
        public void describeMismatch(Object item, Description description) {
            Response response = (Response) item;
            provideDescription(response, description);
        }

    };
}
MigrationClientTest.java 文件源码 项目:henicea 阅读 40 收藏 0 点赞 0 评论 0
@Test
public void getAppliedMigrations_shouldQueryAndSortByName() throws Exception {
    ResultSet appliedMigrationResultSet = mock(ResultSet.class);
    Row row = mock(Row.class);

    when(session.execute(argThat(new CustomMatcher<Insert>("Get applied migrations") {
        @Override
        public boolean matches(Object item) {
            return "SELECT name,status FROM test.migrations;".equals(item.toString());
        }
    }))).thenReturn(appliedMigrationResultSet);
    when(appliedMigrationResultSet.all()).thenReturn(Collections.singletonList(row));
    when(row.getString(0)).thenReturn("001_initial_migration.cql");
    when(row.getString(1)).thenReturn("APPLIED");

    assertThat(client.getAppliedMigrations()).containsOnly("001_initial_migration.cql");
}
MigrationClientTest.java 文件源码 项目:henicea 阅读 30 收藏 0 点赞 0 评论 0
@Test
public void getAppliedMigrations_shouldIgnoreFailedAndIncompleteMigrations() throws Exception {
    ResultSet appliedMigrationResultSet = mock(ResultSet.class);
    Row row1 = mock(Row.class);
    Row row2 = mock(Row.class);

    when(session.execute(argThat(new CustomMatcher<Insert>("Get applied migrations") {
        @Override
        public boolean matches(Object item) {
            return "SELECT name,status FROM test.migrations;".equals(item.toString());
        }
    }))).thenReturn(appliedMigrationResultSet);
    when(appliedMigrationResultSet.all()).thenReturn(Arrays.asList(row1, row2));

    when(row1.getString(0)).thenReturn("001_initial_migration.cql");
    when(row1.getString(1)).thenReturn("APPLIED");
    when(row2.getString(0)).thenReturn("002_add_stuff.cql");
    when(row2.getString(1)).thenReturn("FAILED");

    assertThat(client.getAppliedMigrations()).containsOnly("001_initial_migration.cql");
}
LambdaMatcherTest.java 文件源码 项目:mockito-java8 阅读 43 收藏 0 点赞 0 评论 0
@Test
public void customMatcherShouldBeMoreCompact() {
    //when
    int numberOfShips = ts.findNumberOfShipsInRangeByCriteria(searchCriteria);
    //then
    assertThat(numberOfShips).isZero();
    //and
    verify(ts).findNumberOfShipsInRangeByCriteria(argThat(new HamcrestArgumentMatcher<>(
            new CustomMatcher<ShipSearchCriteria>("ShipSearchCriteria minimumRange<2000 and numberOfPhasers>2") {
                @Override
                public boolean matches(Object item) {
                    ShipSearchCriteria criteria = (ShipSearchCriteria) item;
                    return criteria.getMinimumRange() < 2000 && criteria.getNumberOfPhasers() > 2;
                }
            })));
}
ImageClientUploadTest.java 文件源码 项目:loli.io 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void testGetToken() throws Exception {
    User user = UserServiceTest.newInstence();
    us.save(user);
    mockMvc
        .perform(
            post("/api/token").param("email", user.getEmail()).param("password", user.getPassword())
                .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))).andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8")))
        .andExpect(jsonPath("$.token").value(
        // 匿名内部类,自定义Matcher,判断返回的json文的token属性是否是32个字符长的md5密文
            new CustomMatcher<String>("长度为32的字符串") {
                public boolean matches(Object object) {
                    return ((object instanceof String) && !((String) object).isEmpty() && ((String) object)
                        .length() == 32);
                }
            }));
}
TestUtils.java 文件源码 项目:androidclient 阅读 32 收藏 0 点赞 0 评论 0
public static Matcher<View> withMessageDirection(final int direction) {
    return new CustomMatcher<View>("with message direction: ") {
        @Override
        public boolean matches(Object item) {
            if (!(item instanceof AdapterView)) {
                return false;
            }

            Adapter adapter = ((AdapterView) item).getAdapter();
            for (int i = 0; i < adapter.getCount(); i++) {
                Cursor message = (Cursor) adapter.getItem(i);
                if (message != null && MessageUtils.getMessageDirection(message) == direction) {
                    return true;
                }
            }
            return false;
        }
    };
}
TestUtils.java 文件源码 项目:androidclient 阅读 36 收藏 0 点赞 0 评论 0
public static Matcher<View> withMessageContent(final Context context, final String content) {
    return new CustomMatcher<View>("with message content: ") {
        @Override
        public boolean matches(Object item) {
            if (!(item instanceof AdapterView)) {
                return false;
            }

            Adapter adapter = ((AdapterView) item).getAdapter();
            for (int i = 0; i < adapter.getCount(); i++) {
                Cursor cursor = (Cursor) adapter.getItem(i);
                if (cursor != null) {
                    CompositeMessage message = CompositeMessage.fromCursor(context, cursor);
                    TextComponent text = message.getComponent(TextComponent.class);
                    if (text != null && text.getContent().equalsIgnoreCase(content)) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
}
AisTrackServiceTest.java 文件源码 项目:AisTrack 阅读 33 收藏 0 点赞 0 评论 0
/** Test all targets can be extracted from tracker */
@Test
public void testThatAllExpectedMmsisAreReturnedByTracker() throws Exception {
    Set<TargetInfo> targets = aisTrackService.targets();

    int[] mmsis = targets.stream().mapToInt(t -> t.getMmsi()).distinct().toArray();

    for (int mmsi : mmsis) {
        assertThat(mmsi, new CustomMatcher<Integer>("Tracked MMSI must in in list of expected MMSI's") {
            @Override
            public boolean matches(Object o) {
                for (int i = 0; i < mmsiInTestData.length; i++) {
                    if (mmsiInTestData[i] == mmsi)
                        return true;
                }
                return false;
            }
        });
    }
}
MetricArrayToBytesEncoderTest.java 文件源码 项目:statsd-netty 阅读 22 收藏 0 点赞 0 评论 0
static Matcher<List<Object>> containsBufferFor(MetricValue[]... metricsArgs) {
    return new CustomMatcher<List<Object>>("Contains buffers for the specicied metrics") {

        @Override
        public boolean matches(Object item) {
            @SuppressWarnings("unchecked")
            List<String> items = ((List<Object>) item).stream()
                    .map((x) -> ((ByteBuf) x).toString(StandardCharsets.UTF_8)).collect(Collectors.toList());
            if (metricsArgs.length != items.size()) {
                return false;
            }

            for (MetricValue[] metrics : metricsArgs) {
                String payload = Arrays.asList(metrics).stream().map(MetricToBytesEncoder::toString)
                        .collect(Collectors.joining("\n"));

                if (!items.contains(payload)) {
                    return false;
                }
            }
            return true;
        }
    };

}
PortTest.java 文件源码 项目:openstack-maven-CIET-students 阅读 34 收藏 0 点赞 0 评论 0
@Test
public void testDeserializationAfterSerialization() throws Exception {
    testSerialization();
    Port port = objectMapper.readValue(serializedPort, Port.class);

    assertThat(port.getAdminStateUp(), is(equalTo(ADMIN_STATE_UP)));
    assertThat(port.getDeviceId(), is(equalTo(DEVICE_ID)));
    assertThat(port.getDeviceOwner(), is(equalTo(DEVICE_OWNER)));
    assertThat(port.getMacAddress(), is(equalTo(MAC_ADDRESS)));
    assertThat(port.getName(), is(equalTo(NAME)));
    assertThat(port.getNetworkId(), is(equalTo(NETWORK_ID)));
    assertThat(port.getTenantId(), is(equalTo(TENANT_ID)));

    assertThat(port.getSecurityGroups(), hasItem(equalTo(SEC_GROUP)));
    assertThat(port.getList(), hasItem(new CustomMatcher<Ip>(
            "an Ip object with address " + IP_ADDRESS + " and subnet id " + IP_SUBNET_ID) {

        @Override
        public boolean matches(Object ip) {
            return ip instanceof Ip
                    && IP_ADDRESS.equals(((Ip) ip).getAddress())
                    && IP_SUBNET_ID.equals(((Ip) ip).getSubnetId());
        }
    }));
}
SubnetTest.java 文件源码 项目:openstack-maven-CIET-students 阅读 30 收藏 0 点赞 0 评论 0
@Test
public void testDeserializationAfterSerialization() throws Exception {
    testSerialization();
    Subnet subnet = objectMapper.readValue(serializedSubnet, Subnet.class);

    assertThat(subnet.getCidr(), is(equalTo(CIDR)));
    assertThat(subnet.getDnsNames(), hasItem(equalTo(DNS_SERVER)));
    assertThat(subnet.isEnableDHCP(), is(equalTo(ENABLE_DHCP)));
    assertThat(subnet.getIpversion(), is(equalTo(IP_VERSION)));
    assertThat(subnet.getGw(), is(equalTo(GATEWAY)));
    assertThat(subnet.getHostRoutes(), hasItem(equalTo(HOST_ROUTE)));
    assertThat(subnet.getName(), is(equalTo(NAME)));
    assertThat(subnet.getNetworkId(), is(equalTo(NETWORK_ID)));
    assertThat(subnet.getTenantId(), is(equalTo(TENANT_ID)));
    assertThat(subnet.getList(), hasItem(new CustomMatcher<Pool>(
            "a Pool object with start " + POOL_START + " and end " + POOL_END) {

        @Override
        public boolean matches(Object pool) {
            return pool instanceof Pool
                    && POOL_START.equals(((Pool) pool).getStart())
                    && POOL_END.equals(((Pool) pool).getEnd());
        }
    }));
}
MkIssueTest.java 文件源码 项目:jcabi-github 阅读 28 收藏 0 点赞 0 评论 0
/**
 * MkIssue can list its labels.
 * @throws Exception If some problem inside
 */
@Test
public void listsReadOnlyLabels() throws Exception {
    final Issue issue = this.issue();
    final String tag = "test-tag";
    issue.repo().labels().create(tag, "c0c0c0");
    issue.labels().add(Collections.singletonList(tag));
    MatcherAssert.assertThat(
        new Issue.Smart(issue).roLabels().iterate(),
        Matchers.<Label>hasItem(
            new CustomMatcher<Label>("label just created") {
                @Override
                public boolean matches(final Object item) {
                    return Label.class.cast(item).name().equals(tag);
                }
            }
        )
    );
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 42 收藏 0 点赞 0 评论 0
@Test
public void testGetItemNotFound() throws Exception
{
  expectedException.expect(new CustomMatcher<Object>(ResourceDoesNotExistException.class.getName())
  {
    @Override
    public boolean matches(Object item)
    {
      return item instanceof ResourceDoesNotExistException;
    }
  });
  final HttpClient client = strictMock(HttpClient.class);
  final Storage storage = createStrictMock(Storage.class);
  final GSWagon gsWagon = new GSWagon()
  {
    @Override
    void get(Blob blob, File file) throws IOException, TransferFailedException
    {
      // noop
    }
  };

  gsWagon.swapAndCloseConnection(new ConnectionPOJO(
      storage,
      BLOB_ID,
      client
  ));
  expect(storage.get(EasyMock.<BlobId>anyObject())).andReturn(null).once();
  replay(storage);
  final File outFile = temporaryFolder.newFile();
  gsWagon.get("artifact", outFile);
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 31 收藏 0 点赞 0 评论 0
@Test
public void testBuildStorageFailsWithoutProjectID()
{
  final GSWagon gsWagon = new GSWagon()
  {
    public Repository getRepository()
    {
      return new Repository("id", "url");
    }
  };
  gsWagon.swapAndCloseConnection(connectionPOJO);
  final String property = gsWagon.getPropertyString(gsWagon.getRepository().getId());
  final String pre = System.getProperty(property);
  try {
    expectedException.expect(new CustomMatcher<Object>(NullPointerException.class.getName())
    {
      @Override
      public boolean matches(Object item)
      {
        return item instanceof NullPointerException;
      }
    });
    System.clearProperty(property);
    gsWagon.swapAndCloseConnection(connectionPOJO);
    assertNotNull(gsWagon.buildStorage(connectionPOJO.client));
  }
  finally {
    if (pre != null) {
      System.setProperty(property, pre);
    } else {
      System.clearProperty(property);
    }
  }
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 35 收藏 0 点赞 0 评论 0
@Test
public void testBuildPropertyNPE()
{
  expectedException.expect(new CustomMatcher<Object>(NullPointerException.class.getName())
  {
    @Override
    public boolean matches(Object item)
    {
      return item instanceof NullPointerException;
    }
  });
  gsWagon.getPropertyString(null);
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 49 收藏 0 点赞 0 评论 0
@Test
public void testTranslateNotFound() throws Exception
{
  expectedException.expect(new CustomMatcher(ResourceDoesNotExistException.class.getName())
  {
    @Override
    public boolean matches(Object o)
    {
      return o instanceof ResourceDoesNotExistException;
    }
  });
  throw GSWagon.translate("foo", new StorageException(404, "bad"));
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 34 收藏 0 点赞 0 评论 0
@Test
public void testTranslateBadAuth401() throws Exception
{
  expectedException.expect(new CustomMatcher(AuthorizationException.class.getName())
  {
    @Override
    public boolean matches(Object o)
    {
      return o instanceof AuthorizationException;
    }
  });
  throw GSWagon.translate("foo", new StorageException(401, "bad"));
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 28 收藏 0 点赞 0 评论 0
@Test
public void testTranslateBadAuth403() throws Exception
{
  expectedException.expect(new CustomMatcher(AuthorizationException.class.getName())
  {
    @Override
    public boolean matches(Object o)
    {
      return o instanceof AuthorizationException;
    }
  });
  throw GSWagon.translate("foo", new StorageException(403, "bad"));
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 28 收藏 0 点赞 0 评论 0
@Test
public void testTranslateRetryable() throws Exception
{
  expectedException.expect(new CustomMatcher(TransferFailedException.class.getName())
  {
    @Override
    public boolean matches(Object o)
    {
      return o instanceof TransferFailedException;
    }
  });
  final StorageException se = new StorageException(429, "foo");
  assertTrue(se.isRetryable());
  throw GSWagon.translate("foo", se);
}
GSWagonTest.java 文件源码 项目:gswagon-maven-plugin 阅读 29 收藏 0 点赞 0 评论 0
@Test
public void testTranslateUnknownType() throws Exception
{
  expectedException.expect(new CustomMatcher(TransferFailedException.class.getName())
  {
    @Override
    public boolean matches(Object o)
    {
      return o instanceof TransferFailedException;
    }
  });
  final StorageException se = new StorageException(455, "foo");
  assertFalse(se.isRetryable());
  throw GSWagon.translate("foo", se);
}


问题


面经


文章

微信
公众号

扫码关注公众号