Java Examples for org.hamcrest.Matchers
The following java examples will help you to understand the usage of org.hamcrest.Matchers. These source code samples are taken from different open source projects.
Example 1
| Project: RUT-master File: TrieTest.java View source code |
@Test
public void testToString() {
assertThat(trie.toString(), not(Matchers.isEmptyOrNullString()));
trie.insert(Path.of("/"), "/");
assertThat(trie.toString(), not(Matchers.isEmptyOrNullString()));
trie.insert(Path.of("/<foo>"), "/<foo>");
assertThat(trie.toString(), not(Matchers.isEmptyOrNullString()));
trie.insert(Path.of("/<foo>/<bar:path>"), "/<foo>/<bar:path>");
assertThat(trie.toString(), not(Matchers.isEmptyOrNullString()));
}Example 2
| Project: zava-master File: HelloWorldStrategyContextTest.java View source code |
@Test
public void testHelloWorldStrategyContext() {
HelloWorldStrategyContext helloWorldStrategyContext = new HelloWorldStrategyContext(new JavaHelloWorldStrategy());
MatcherAssert.assertThat(helloWorldStrategyContext.helloWorld(), Matchers.is("Hello Java!"));
helloWorldStrategyContext = new HelloWorldStrategyContext(new DesignPatternHelloWorldStrategy());
MatcherAssert.assertThat(helloWorldStrategyContext.helloWorld(), Matchers.is("Hello Strategy!"));
}Example 3
| Project: snotel-master File: TestAutoConfiguration.java View source code |
@Test
public void disableAutoConfiguration() {
SpringApplication springApplication = new SpringApplication(AutoConfiguration.class);
springApplication.setAdditionalProfiles("disableAutoConfig");
try (ConfigurableApplicationContext context = springApplication.run()) {
assertThat(context.getBeansOfType(MetronClient.class).entrySet(), Matchers.iterableWithSize(0));
}
}Example 4
| Project: subtitles4j-master File: ASSFactoryTest.java View source code |
@Test
@SubtitlesFile(type = SubtitlesType.ASS, name = "test1")
public void testFromFileOk() throws Exception {
SubtitlesContainer container = factory.fromFile(subtitlesFileHandler.getFile());
Assert.assertNotNull(container);
Assert.assertEquals(container.getTitle(), "A title");
Assert.assertEquals(container.getAuthor(), "Toyo");
Assert.assertNotNull(container.getStyles());
Assert.assertNotNull(container.getStyles().get("Default"));
Assert.assertThat(container.getStyles().get("Default"), allOf(hasEntry(is(StyleProperty.FONT_NAME), is("Arial")), hasEntry(is(StyleProperty.FONT_SIZE), is("25")), hasEntry(is(StyleProperty.PRIMARY_COLOR), is("&H00FFFFFF")), hasEntry(is(StyleProperty.SECONDARY_COLOR), is("&H000000FF")), hasEntry(is(StyleProperty.OUTLINE_COLOR), is("&H00000000")), hasEntry(is(StyleProperty.BACK_COLOR), is("&H00000000")), hasEntry(is(StyleProperty.BOLD), is("0")), hasEntry(is(StyleProperty.ITALIC), is("0")), hasEntry(is(StyleProperty.UNDERLINE), is("0")), hasEntry(is(StyleProperty.STRIKEOUT), is("0")), hasEntry(is(StyleProperty.SCALE_X), is("100")), hasEntry(is(StyleProperty.SCALE_Y), is("100")), hasEntry(is(StyleProperty.SPACING), is("0")), hasEntry(is(StyleProperty.ANGLE), is("0")), hasEntry(is(StyleProperty.BORDER_STYLE), is("1")), hasEntry(is(StyleProperty.OUTLINE), is("2")), hasEntry(is(StyleProperty.SHADOW), is("1")), hasEntry(is(StyleProperty.ALIGNMENT), is("2")), hasEntry(is(StyleProperty.MARGIN_L), is("10")), hasEntry(is(StyleProperty.MARGIN_R), is("10")), hasEntry(is(StyleProperty.MARGIN_V), is("10")), hasEntry(is(StyleProperty.ENCODING), is("1"))));
Assert.assertNotNull(container.getCaptions());
Assert.assertThat(container.getCaptions(), allOf(not(empty()), contains(allOf(instanceOf(Caption.class), hasProperty("start", is(1230L)), hasProperty("end", is(4560L)), hasProperty("lines", allOf(not(Matchers.<String>empty()), Matchers.<String>contains("Line 1")))), allOf(instanceOf(Caption.class), hasProperty("start", is(2340L)), hasProperty("end", is(5670L)), hasProperty("lines", allOf(not(Matchers.<String>empty()), Matchers.<String>contains("Line 1", "Line 2")))), allOf(instanceOf(Caption.class), hasProperty("start", is(3450L)), hasProperty("end", is(6780L)), hasProperty("lines", allOf(not(Matchers.<String>empty()), Matchers.<String>contains("Line 1", "Line 2", "Line 3")))))));
}Example 5
| Project: raven-java-master File: EventTest.java View source code |
@Test
public void serializedEventContainsSerializableExtras(@Injectable final Object nonSerializableObject) throws Exception {
final Event event = new Event(UUID.fromString("fb3fe928-69af-41a5-b76b-1db4c324caf6"));
new NonStrictExpectations() {
{
nonSerializableObject.toString();
result = "3c644639-9721-4e32-8cc8-a2b5b77f4424";
}
};
event.getExtra().put("SerializableEntry", 38295L);
event.getExtra().put("NonSerializableEntry", nonSerializableObject);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(event);
ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
Event receivedEvent = (Event) is.readObject();
assertThat(receivedEvent.getId(), equalTo(event.getId()));
assertThat(receivedEvent.getExtra().get("SerializableEntry"), Matchers.<Object>equalTo(38295L));
assertThat(receivedEvent.getExtra().get("NonSerializableEntry"), Matchers.<Object>equalTo("3c644639-9721-4e32-8cc8-a2b5b77f4424"));
}Example 6
| Project: spring-open-master File: MatchActionOperationsTest.java View source code |
/**
* Test that dependencies can be added to operations.
*/
@Test
public void testMatchActionOperationsDependencies() {
final MatchActionOperationsId id = new MatchActionOperationsId(12345678L);
final MatchActionOperations operations = new MatchActionOperations(id);
assertThat(operations.getDependencies(), hasSize(0));
operations.addDependency(new MatchActionOperationsId(1L));
assertThat(operations.getDependencies(), hasSize(1));
operations.addDependency(new MatchActionOperationsId(2L));
assertThat(operations.getDependencies(), hasSize(2));
operations.addDependency(new MatchActionOperationsId(3L));
final Set<MatchActionOperationsId> operationEntries = operations.getDependencies();
assertThat(operationEntries, hasSize(3));
final long[] expectedIds = { 1, 2, 3 };
for (long expectedId : expectedIds) {
assertThat(operationEntries, hasItem(Matchers.<MatchActionOperationsId>hasProperty("id", equalTo(expectedId))));
}
}Example 7
| Project: git-java-practice-master File: OrderStatusIntegrationTest.java View source code |
@Test
public void thatOrderStatusIsPutInModel() throws Exception {
when(orderService.requestOrderDetails(any(RequestOrderDetailsEvent.class))).thenReturn(orderDetailsEvent(uuid));
when(orderService.requestOrderStatus(any(RequestOrderStatusEvent.class))).thenReturn(orderStatusEvent(uuid));
mockMvc.perform(get("/order/" + uuid)).andExpect(model().attributeExists("orderStatus")).andExpect(model().attribute("orderStatus", hasProperty("name", equalTo(WebDataFixture.CUSTOMER_NAME)))).andExpect(model().attribute("orderStatus", hasProperty("status", equalTo(WebDataFixture.STATUS_RECEIVED))));
verify(orderService).requestOrderDetails(Matchers.<RequestOrderDetailsEvent>argThat(org.hamcrest.Matchers.<RequestOrderDetailsEvent>hasProperty("key", equalTo(uuid))));
verify(orderService).requestOrderStatus(any(RequestOrderStatusEvent.class));
}Example 8
| Project: YummyNoodleBar-master File: OrderStatusIntegrationTest.java View source code |
@Test
public void thatOrderStatusIsPutInModel() throws Exception {
when(orderService.requestOrderDetails(any(RequestOrderDetailsEvent.class))).thenReturn(orderDetailsEvent(uuid));
when(orderService.requestOrderStatus(any(RequestOrderStatusEvent.class))).thenReturn(orderStatusEvent(uuid));
mockMvc.perform(get("/order/" + uuid)).andExpect(model().attributeExists("orderStatus")).andExpect(model().attribute("orderStatus", hasProperty("name", equalTo(WebDataFixture.CUSTOMER_NAME)))).andExpect(model().attribute("orderStatus", hasProperty("status", equalTo(WebDataFixture.STATUS_RECEIVED))));
verify(orderService).requestOrderDetails(Matchers.<RequestOrderDetailsEvent>argThat(org.hamcrest.Matchers.<RequestOrderDetailsEvent>hasProperty("key", equalTo(uuid))));
verify(orderService).requestOrderStatus(any(RequestOrderStatusEvent.class));
}Example 9
| Project: ElasticRawClient-master File: ElasticClientUpdateDocumentTest.java View source code |
// region Happy path
@Test
public void updateDocumentTest() {
try {
String cityId = "karcag";
SimpleCity city = new SimpleCity("karcagTest");
client.updateDocument(cityId, city);
Thread.sleep(1000);
List<SimpleCity> cities = client.getDocument(new String[] { cityId }, SimpleCity.class);
assertThat(cities, not(nullValue()));
assertThat(cities.size(), equalTo(1));
assertThat(cities, hasItem(Matchers.<SimpleCity>hasProperty("name", equalTo("karcagTest"))));
SimpleCity retCity = new SimpleCity("Karcag");
client.updateDocument(cityId, retCity);
Thread.sleep(1000);
List<SimpleCity> retCities = client.getDocument(new String[] { cityId }, SimpleCity.class);
assertThat(retCities, not(nullValue()));
assertThat(retCities.size(), equalTo(1));
assertThat(retCities, hasItem(Matchers.<SimpleCity>hasProperty("name", equalTo("Karcag"))));
} catch (IndexCannotBeNullExceptionTypeCannotBeNullException | e) {
e.printStackTrace();
fail(e.getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
fail(e.getMessage());
}
}Example 10
| Project: jbehave-core-master File: FrSteps.java View source code |
@Then("les valeurs multipliées par $multiplier sont: $table")
public void theResultsMultipliedByAre(int multiplier, ExamplesTable results) {
OutcomesTable outcomes = new OutcomesTable(new LocalizedKeywords(new Locale("fr")));
for (int row = 0; row < results.getRowCount(); row++) {
Parameters expected = results.getRowAsParameters(row);
Parameters original = table.getRowAsParameters(row);
int one = original.valueAs("un", Integer.class);
int two = original.valueAs("deux", Integer.class);
outcomes.addOutcome("un", one * multiplier, Matchers.equalTo(expected.valueAs("un", Integer.class)));
outcomes.addOutcome("deux", two * multiplier, Matchers.equalTo(expected.valueAs("deux", Integer.class)));
}
outcomes.verify();
}Example 11
| Project: jqassistant-master File: LinecountScannerPluginTest.java View source code |
@Test
public void thatConfiguredSuffixesWereAccepted() throws Exception {
linecountScannerPlugin.acceptSuffixes("java, xml");
assertThat("java suffix is configured and should be accepted", linecountScannerPlugin.accepts(null, "File.java", null), Matchers.is(true));
assertThat("xml suffix is configured and should be accepted", linecountScannerPlugin.accepts(null, "File.xml", null), Matchers.is(true));
assertThat("suffix should not be case sensitive", linecountScannerPlugin.accepts(null, "File.XML", null), Matchers.is(true));
}Example 12
| Project: jqassistant-plugins-master File: LinecountScannerPluginTest.java View source code |
@Test
public void thatConfiguredSuffixesWereAccepted() throws Exception {
linecountScannerPlugin.acceptSuffixes("java, xml");
assertThat("java suffix is configured and should be accepted", linecountScannerPlugin.accepts(null, "File.java", null), Matchers.is(true));
assertThat("xml suffix is configured and should be accepted", linecountScannerPlugin.accepts(null, "File.xml", null), Matchers.is(true));
assertThat("suffix should not be case sensitive", linecountScannerPlugin.accepts(null, "File.XML", null), Matchers.is(true));
}Example 13
| Project: puree-android-master File: RecordsTest.java View source code |
@Test
public void getJsonLogs() {
{
Records records = new Records();
assertThat(records.getJsonLogs().size(), Matchers.is(0));
}
{
Records records = new Records();
for (int i = 0; i < 3; i++) {
records.add(new Record(i, "logcat", new JsonObject()));
}
assertThat(records.getJsonLogs().size(), is(3));
}
}Example 14
| Project: sandboxes-master File: ValidationInIsolationTest.java View source code |
@Test
public void testLicensePlateNotUpperCase() {
BeanToValidate beanToValidate = new BeanToValidate();
Set<ConstraintViolation<BeanToValidate>> constraintViolations = validator.validate(beanToValidate);
assertThat(constraintViolations, Matchers.hasSize(1));
assertThat(constraintViolations.iterator().next().getMessage(), is("do not touch this"));
}Example 15
| Project: sw360portal-master File: PortletUtilsTest.java View source code |
@Test
public void testSplitToSet() throws Exception {
Set<String> setOne = splitToSet("a, , b , ");
assertThat(setOne, Matchers.containsInAnyOrder("a", "b"));
assertThat(splitToSet("a, b,"), containsInAnyOrder("a", "b"));
assertThat(splitToSet("a, b,"), containsInAnyOrder("a", "b"));
assertThat(splitToSet("b, a, b , a b"), containsInAnyOrder("a", "a b", "b"));
}Example 16
| Project: vraptor-master File: DefaultUploadedFileTest.java View source code |
@Test
public void usingUnixLikeSeparators() throws Exception {
DefaultUploadedFile file = new DefaultUploadedFile(CONTENT, "/a/unix/path/file.txt", "text/plain", 0);
assertThat(file.getFileName(), is("file.txt"));
assertThat(file.getCompleteFileName(), is("/a/unix/path/file.txt"));
assertThat(file.toString(), Matchers.containsString(file.getFileName()));
}Example 17
| Project: collections-utils-master File: MeasurementTest.java View source code |
@Test
public void measuresObjects() {
MatcherAssert.assertThat(new Measurement<>(String::length).compare("looooooooong", "short"), Matchers.equalTo(1));
MatcherAssert.assertThat(new Measurement<>(String::length).compare("short", "looooooong"), Matchers.equalTo(-1));
MatcherAssert.assertThat(new Measurement<>(String::length).compare("two", "one"), Matchers.equalTo(0));
}Example 18
| Project: document-viewer-master File: BookSettingsTest.java View source code |
@Test
public void testLoadv277Book() {
JSONObject json = TestUtils.parseJSON(openAssetAsString("book-v2.7.7.json"));
BookSettings bs;
try {
bs = new BookSettings(json);
} catch (JSONException e) {
throw new RuntimeException(e);
}
assertThat(bs, is(notNullValue()));
assertThat(bs.persistent, is(true));
assertThat(bs.lastChanged, is(0L));
assertThat(bs.fileName, is("x.pdf"));
assertThat(bs.lastUpdated, is(1477463637283L));
assertThat(bs.firstPageOffset, is(1));
assertThat(bs.currentPage, is(new PageIndex(2, 2)));
assertThat(bs.zoom, is(100));
assertThat(bs.splitPages, is(false));
assertThat(bs.splitRTL, is(false));
assertThat(bs.rotation, is(RotationType.UNSPECIFIED));
assertThat(bs.viewMode, is(DocumentViewMode.VERTICALL_SCROLL));
assertThat(bs.pageAlign, is(PageAlign.WIDTH));
assertThat(bs.animationType, is(PageAnimationType.NONE));
assertThat(bs.bookmarks, is(Matchers.<Bookmark>empty()));
assertThat(bs.cropPages, is(false));
assertThat(bs.offsetX, is(0f));
assertThat(bs.offsetY, is(0.4187299907207489f));
assertThat(bs.nightMode, is(false));
assertThat(bs.positiveImagesInNightMode, is(false));
assertThat(bs.contrast, is(100));
assertThat(bs.gamma, is(100));
assertThat(bs.exposure, is(100));
assertThat(bs.autoLevels, is(false));
assertThat(bs.typeSpecific, is(nullValue()));
}Example 19
| Project: pedantic-pom-enforcers-master File: PriorityOrderingTest.java View source code |
@Test
public void testCompare() {
ArrayList<String> prioritizedItems = Lists.newArrayList("z", "y", "x");
Function<String, String> transformer = Functions.identity();
PriorityOrdering<String, String> testComparator = new PriorityOrdering<>(prioritizedItems, transformer);
// x is in the priority list, a isn't -> a > x
assertThat(testComparator.compare("a", "x"), greaterThan(0));
// x is located after y in the priority list -> x > y
assertThat(testComparator.compare("x", "y"), greaterThan(0));
// x is located after y in the priority list -> y < x
assertThat(testComparator.compare("y", "x"), lessThan(0));
// equality applies to values in the priority list
assertThat(testComparator.compare("x", "x"), Matchers.is(0));
// regular comparison for values that are not in the priority list
assertThat(testComparator.compare("b", "c"), lessThan(0));
assertThat(testComparator.compare("b", "b"), is(0));
assertThat(testComparator.compare("c", "b"), greaterThan(0));
}Example 20
| Project: SquirrelID-master File: HashMapServiceTest.java View source code |
@Test
public void testFindAllByName() throws Exception {
HashMapService resolver = new HashMapService();
UUID notchUuid = UUID.fromString("069a79f4-44e9-4726-a5be-fca90e38aaf5");
UUID jebUuid = UUID.fromString("853c80ef-3c37-49fd-aa49-938b674adae6");
Profile notchProfile = new Profile(notchUuid, "Notch");
Profile jebProfile = new Profile(jebUuid, "jeb_");
assertThat(resolver.findByName("Notch"), equalTo(null));
assertThat(resolver.findAllByName(Arrays.asList("Notch")), Matchers.<Profile>hasSize(0));
resolver.put(notchProfile);
assertThat(resolver.findByName("Notch"), equalTo(notchProfile));
assertThat(resolver.findAllByName(Arrays.asList("Notch")), allOf(Matchers.<Profile>hasSize(1), containsInAnyOrder(notchProfile)));
assertThat(resolver.findAllByName(Arrays.asList("Notch", "jeb_")), allOf(Matchers.<Profile>hasSize(1), containsInAnyOrder(notchProfile)));
resolver.put(jebProfile);
assertThat(resolver.findAllByName(Arrays.asList("Notch", "jeb_")), allOf(Matchers.<Profile>hasSize(2), containsInAnyOrder(notchProfile, jebProfile)));
assertThat(resolver.findAllByName(Arrays.asList("!__@#%*@#^(@6__NOBODY____", "jeb_")), allOf(Matchers.<Profile>hasSize(1), containsInAnyOrder(jebProfile)));
}Example 21
| Project: android-test-kit-master File: ViewInteractionTest.java View source code |
@Override
public void setUp() throws Exception {
super.setUp();
initMocks(this);
realLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance();
rootView = new View(getContext());
targetView = new View(getContext());
viewMatcher = is(targetView);
actionConstraint = Matchers.<View>notNullValue();
rootMatcherRef = new AtomicReference<Matcher<Root>>(RootMatchers.DEFAULT);
when(mockAction.getDescription()).thenReturn("A Mock!");
failureHandler = new FailureHandler() {
@Override
public void handle(Throwable error, Matcher<View> viewMatcher) {
propagate(error);
}
};
}Example 22
| Project: double-espresso-master File: ViewInteractionTest.java View source code |
@Override
public void setUp() throws Exception {
super.setUp();
initMocks(this);
realLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance();
rootView = new View(getContext());
targetView = new View(getContext());
viewMatcher = is(targetView);
actionConstraint = Matchers.<View>notNullValue();
rootMatcherRef = new AtomicReference<Matcher<Root>>(RootMatchers.DEFAULT);
when(mockAction.getDescription()).thenReturn("A Mock!");
failureHandler = new FailureHandler() {
@Override
public void handle(Throwable error, Matcher<View> viewMatcher) {
propagate(error);
}
};
}Example 23
| Project: elassandra-master File: KeyedLockTests.java View source code |
public void testIfMapEmptyAfterLotsOfAcquireAndReleases() throws InterruptedException {
ConcurrentHashMap<String, Integer> counter = new ConcurrentHashMap<>();
ConcurrentHashMap<String, AtomicInteger> safeCounter = new ConcurrentHashMap<>();
KeyedLock<String> connectionLock = new KeyedLock<String>(randomBoolean());
String[] names = new String[randomIntBetween(1, 40)];
for (int i = 0; i < names.length; i++) {
names[i] = randomRealisticUnicodeOfLengthBetween(10, 20);
}
CountDownLatch startLatch = new CountDownLatch(1);
int numThreads = randomIntBetween(3, 10);
AcquireAndReleaseThread[] threads = new AcquireAndReleaseThread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new AcquireAndReleaseThread(startLatch, connectionLock, names, counter, safeCounter);
}
for (int i = 0; i < numThreads; i++) {
threads[i].start();
}
startLatch.countDown();
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
assertThat(connectionLock.hasLockedKeys(), equalTo(false));
Set<Entry<String, Integer>> entrySet = counter.entrySet();
assertThat(counter.size(), equalTo(safeCounter.size()));
for (Entry<String, Integer> entry : entrySet) {
AtomicInteger atomicInteger = safeCounter.get(entry.getKey());
assertThat(atomicInteger, not(Matchers.nullValue()));
assertThat(atomicInteger.get(), equalTo(entry.getValue()));
}
}Example 24
| Project: MutabilityDetector-master File: NamesFromClassResourcesTest.java View source code |
@Test
public void appliesGivenRegularExpressionToFilterOutClassNames() throws Exception {
String[] resources = { "com/some/classfile/FindMe.class", "com/some/classfile/IgnoreThis.class" };
NamesFromClassResources toAnalyse = new NamesFromClassResources(".*FindMe.*");
assertThat(toAnalyse.asDotted(resources), allOf(contains(aDottedClassNameOf("com.some.classfile.FindMe")), Matchers.<Dotted>iterableWithSize(1)));
}Example 25
| Project: ngrinder-master File: MonitorClientServiceTest.java View source code |
@Test
public void testMonitorClient() throws IOException {
MonitorClientService client = new MonitorClientService("127.0.0.1", 13243);
client.init();
final SystemInfo monitorData = client.getSystemInfo();
assertThat(monitorData.isParsed(), is(false));
sleep(3000);
client.update();
SystemInfo monitorData2 = client.getSystemInfo();
assertThat(monitorData2.isParsed(), is(true));
assertThat(monitorData2, Matchers.notNullValue());
assertThat(monitorData, not(monitorData2));
}Example 26
| Project: Permission-Nanny-master File: NannyBundleTest.java View source code |
@Test
public void builder_shouldFormatBundleAccordingToPPP() throws Exception {
mEntityBody.putString("customKey", "val");
Bundle actual = simpleBundle();
assertThat(actual.getString(Nanny.PROTOCOL_VERSION), is(Nanny.PPP_0_1));
assertThat(actual.getInt(Nanny.STATUS_CODE), is(1));
assertThat(actual.getString(Nanny.CLIENT_ADDRESS), is("a"));
assertThat(actual.getString(Nanny.CONNECTION), is("b"));
assertThat(actual.getString(Nanny.SERVER), is("c"));
assertThat(actual.getSerializable(Nanny.ENTITY_ERROR), Matchers.<Serializable>sameInstance(mNannyException));
Bundle actualBody = actual.getBundle(Nanny.ENTITY_BODY);
assertThat(actualBody, notNullValue());
assertThat(actualBody.getString("customKey"), is("val"));
assertThat(actualBody.getParcelable(Nanny.SENDER_IDENTITY), Matchers.<Parcelable>sameInstance(mSender));
assertThat(actualBody.getParcelable(Nanny.REQUEST_PARAMS), Matchers.<Parcelable>sameInstance(mRequestParams));
assertThat(actualBody.getString(Nanny.REQUEST_RATIONALE), is("d"));
assertThat(actualBody.getString(Nanny.REQUEST_REASON), is("d"));
assertThat(actualBody.getString(Nanny.DEEP_LINK_TARGET), is("e"));
assertThat(actualBody.getString(Nanny.ACK_SERVER_ADDRESS), is("f"));
}Example 27
| Project: JFramework-master File: JMatchers.java View source code |
public static <T extends java.lang.Comparable<T>> org.hamcrest.Matcher<T> isExplicitlyBetween(T value1, T value2) {
String format = "a value is between %0 and %1";
if (value1.compareTo(value2) > 0) {
return DescribedAs.describedAs(format, org.hamcrest.Matchers.allOf(org.hamcrest.Matchers.lessThan(value1), org.hamcrest.Matchers.greaterThan(value2)), value1, value2);
}
return DescribedAs.describedAs(format, org.hamcrest.Matchers.allOf(org.hamcrest.Matchers.lessThan(value2), org.hamcrest.Matchers.greaterThan(value1)), value2, value1);
}Example 28
| Project: blogix-master File: FileDbAccTest.java View source code |
private void assertFirstPost(Post post) {
assertThat(post.getTitle(), is("Sample title"));
assertThat(post.getId(), is("2012-01-30-some-title"));
assertThat(post.getSections(), is(notNullValue()));
assertThat(Arrays.asList(post.getSections()), Matchers.contains("Section 1", "Section 2", "Section 3"));
assertThat(post.getBody(), is("This is just a body\n---------------This is actually not a delimiter"));
assertThat(post.getCommentsEnabled(), is(true));
}Example 29
| Project: ehcache3-master File: ResourcePoolsBuilderTest.java View source code |
@Test
public void testPreExistingWith() throws Exception {
ResourcePoolsBuilder builder = ResourcePoolsBuilder.newResourcePoolsBuilder();
builder = builder.heap(8, MemoryUnit.MB);
try {
builder.with(new SizedResourcePoolImpl<SizedResourcePool>(HEAP, 16, MemoryUnit.MB, false));
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), Matchers.containsString("Can not add 'Pool {16 MB heap}'; configuration already contains 'Pool {8 MB heap}'"));
}
}Example 30
| Project: geowebcache-master File: ParametersUtilsTest.java View source code |
@Test
public void testTwoToKVPSorting() {
// Intentionally make the tree use reverse alphabetical order
Map<String, String> parameters = new TreeMap<>(( s1, s2) -> -s1.compareTo(s2));
parameters.put("test1", "blah1");
parameters.put("test2", "blah2");
String result = ParametersUtils.getKvp(parameters);
// Should be normal alphabetical order
assertThat(result, Matchers.equalTo("test1=blah1&test2=blah2"));
}Example 31
| Project: android-calculatorpp-master File: BasePlotTest.java View source code |
protected void addFunction(@NonNull CppFunction function) {
openFunctionEditor();
if (!TextUtils.isEmpty(function.getName())) {
onView(withId(R.id.function_name)).perform(typeText(function.getName()));
}
for (String parameter : function.getParameters()) {
onView(withId(R.id.function_params_add)).perform(click());
onView(allOf(hasFocus(), withTagValue(Matchers.<Object>equalTo(FunctionParamsView.PARAM_VIEW_TAG)))).perform(click(), typeTextIntoFocusedView(parameter));
}
onView(withId(R.id.function_body)).perform(typeText(function.getBody()));
onView(withText(R.string.cpp_done)).perform(click());
}Example 32
| Project: appmon4j-master File: Appmon4jDumperTest.java View source code |
@Test
public void dumpContainsReportingValues() {
InApplicationMonitor inApplicationMonitor = inApplicationMonitorRule.getInApplicationMonitor();
String counterName = "DummyCounter";
String timerName = "DummyTimer";
String stateValueName = "DummyStateValue";
inApplicationMonitor.incrementCounter(counterName);
inApplicationMonitor.addTimerMeasurement(timerName, 42L);
inApplicationMonitor.registerStateValue(new SimpleStateValueProvider(stateValueName, 42L));
Appmon4jDumper objectUnderTest = new Appmon4jDumper(inApplicationMonitorRule.getInApplicationMonitor());
objectUnderTest.onApplicationEvent(new ContextClosedEvent(new GenericApplicationContext()));
assertThat(loggingEvents, Matchers.<LoggingEvent>hasItem(allOf(loggingEventWithMessageContaining(counterName), loggingEventWithMessageContaining(timerName), loggingEventWithMessageContaining(stateValueName))));
}Example 33
| Project: buck-master File: AsyncCloseableTest.java View source code |
@Test
public void testCloseAsync() throws Exception {
ListeningExecutorService directExecutor = MoreExecutors.newDirectExecutorService();
final AtomicBoolean didClose = new AtomicBoolean(false);
try (AsyncCloseable asyncCloseable = new AsyncCloseable(directExecutor)) {
asyncCloseable.closeAsync(() -> didClose.set(true));
}
assertThat(didClose.get(), Matchers.is(true));
}Example 34
| Project: dbdeploy-master File: DatabaseSchemaVersionManagerTest.java View source code |
@Test
public void shouldGenerateSqlStringContainingSpecifiedChangelogTableNameOnDelete() {
DatabaseSchemaVersionManager schemaVersionManagerWithDifferentTableName = new DatabaseSchemaVersionManager(queryExecuter, "user_specified_changelog");
String updateSql = schemaVersionManagerWithDifferentTableName.getChangelogDeleteSql(script);
assertThat(updateSql, Matchers.startsWith("DELETE FROM user_specified_changelog "));
}Example 35
| Project: elasticsearch-master File: BulkRequestModifierTests.java View source code |
public void testPipelineFailures() {
BulkRequest originalBulkRequest = new BulkRequest();
for (int i = 0; i < 32; i++) {
originalBulkRequest.add(new IndexRequest("index", "type", String.valueOf(i)));
}
TransportBulkAction.BulkRequestModifier modifier = new TransportBulkAction.BulkRequestModifier(originalBulkRequest);
for (int i = 0; modifier.hasNext(); i++) {
modifier.next();
if (i % 2 == 0) {
modifier.markCurrentItemAsFailed(new RuntimeException());
}
}
// So half of the requests have "failed", so only the successful requests are left:
BulkRequest bulkRequest = modifier.getBulkRequest();
assertThat(bulkRequest.requests().size(), Matchers.equalTo(16));
List<BulkItemResponse> responses = new ArrayList<>();
ActionListener<BulkResponse> bulkResponseListener = modifier.wrapActionListenerIfNeeded(1L, new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkItemResponses) {
responses.addAll(Arrays.asList(bulkItemResponses.getItems()));
}
@Override
public void onFailure(Exception e) {
}
});
List<BulkItemResponse> originalResponses = new ArrayList<>();
for (DocWriteRequest actionRequest : bulkRequest.requests()) {
IndexRequest indexRequest = (IndexRequest) actionRequest;
IndexResponse indexResponse = new IndexResponse(new ShardId("index", "_na_", 0), indexRequest.type(), indexRequest.id(), 1, 17, 1, true);
originalResponses.add(new BulkItemResponse(Integer.parseInt(indexRequest.id()), indexRequest.opType(), indexResponse));
}
bulkResponseListener.onResponse(new BulkResponse(originalResponses.toArray(new BulkItemResponse[originalResponses.size()]), 0));
assertThat(responses.size(), Matchers.equalTo(32));
for (int i = 0; i < 32; i++) {
assertThat(responses.get(i).getId(), Matchers.equalTo(String.valueOf(i)));
}
}Example 36
| Project: googleads-java-lib-master File: BatchJobLoggerTest.java View source code |
/**
* Verifies that if all arguments to {@code logUpload} are null, the logger logs a success
* message.
*/
@Test
public void testLogUpload_allNullArgumentsLoggedAsSuccessToInfo() {
batchJobLogger.logUpload(null, null, null, null);
// Verify the INFO level log message is correct.
verify(logger, times(1)).info(Matchers.notNull(String.class), Matchers.contains(BatchJobLogger.SUCCESS_STATUS), Matchers.isNull());
// Verify the DEBUG level log message is correct.
verify(logger, times(1)).debug(Matchers.notNull(String.class), Matchers.contains(BatchJobLogger.SUCCESS_STATUS), Matchers.isNull(), Matchers.isNull());
}Example 37
| Project: hamcrest-nextdeed-master File: InstantiableViaDefaultConstructorTest.java View source code |
@Test
public void messageContainsNoSuchMethodException() throws Exception {
try {
assertThat(NoDefaultConstructor.class, isInstantiableViaDefaultConstructor());
} catch (AssertionError e) {
String message = e.getMessage();
assertThat(message, Matchers.containsString(NoSuchMethodException.class.getSimpleName()));
return;
}
fail("AssertionError should have been raised.");
}Example 38
| Project: Intake-master File: EnumProviderTest.java View source code |
@Test
public void testGetSuggestions() throws Exception {
assertThat(provider.getSuggestions(""), containsInAnyOrder("small", "medium", "large", "very_large"));
assertThat(provider.getSuggestions("s"), containsInAnyOrder("small"));
assertThat(provider.getSuggestions("la"), containsInAnyOrder("large"));
assertThat(provider.getSuggestions("very"), containsInAnyOrder("very_large"));
assertThat(provider.getSuggestions("verylarg"), containsInAnyOrder("very_large"));
assertThat(provider.getSuggestions("very_"), containsInAnyOrder("very_large"));
assertThat(provider.getSuggestions("tiny"), Matchers.<String>empty());
}Example 39
| Project: JDave-master File: SelectionSpec.java View source code |
public void matchesAnythingByDefault() {
checking(new Expectations() {
{
// This expectation does not actually test the third param as it looks like,
// because you can't apparently match Matchers(?).
one(selector).first(with(equalTo(searchContext)), with(equalTo(Component.class)), (Matcher<?>) with(is(anything())));
will(returnValue(returnedComponent));
}
});
specify(selection.from(searchContext), does.equal(returnedComponent));
}Example 40
| Project: platform_build-master File: AsyncCloseableTest.java View source code |
@Test
public void testCloseAsync() throws Exception {
ListeningExecutorService directExecutor = MoreExecutors.newDirectExecutorService();
final AtomicBoolean didClose = new AtomicBoolean(false);
try (AsyncCloseable asyncCloseable = new AsyncCloseable(directExecutor)) {
asyncCloseable.closeAsync(() -> didClose.set(true));
}
assertThat(didClose.get(), Matchers.is(true));
}Example 41
| Project: billing-ng-master File: ValidationExceptionTest.java View source code |
@Test
@SuppressWarnings("unchecked")
public void testValidationExceptionViolations() {
TestEntity entity = new TestEntity();
entity.setId(null);
entity.setString("more than five chars");
ValidationException exception = new ValidationException(entity.validateConstraints());
Set<ConstraintViolation<TestEntity>> constraintViolations = (Set<ConstraintViolation<TestEntity>>) exception.getConstraintViolations();
assertThat(constraintViolations.size(), is(2));
assertThat(constraintViolations, hasItem(Matchers.<ConstraintViolation<TestEntity>>hasProperty("message", is("may not be null"))));
assertThat(constraintViolations, hasItem(Matchers.<ConstraintViolation<TestEntity>>hasProperty("message", is("size must be between 0 and 5"))));
}Example 42
| Project: governator-master File: TestAnnotationFinder.java View source code |
@Test
public void testFindAnnotationsOnConstructors() {
cp.compile("package governator.test;" + "import java.util.Collection;" + "public class Foo {" + " @A private Foo() {}" + " @A Foo(String p) {}" + " @A Foo(String[] p) {}" + " @A Foo(Collection<String> p) {}" + " @A Foo(byte p) {}" + "}");
assertThat(scan("governator.test.Foo", a).getAnnotatedConstructors(), is(Matchers.<Constructor>iterableWithSize(5)));
}Example 43
| Project: metrics-cdi-master File: TimedClassBeanTest.java View source code |
@Test
@InSequence(1)
public void timedMethodsNotCalledYet() {
assertThat("Timers are not registered correctly", registry.getTimers().keySet(), is(equalTo(TIMER_NAMES)));
assertThat("Constructor timer count is incorrect", registry.getTimers().get(CONSTRUCTOR_TIMER_NAME).getCount(), is(equalTo(1L)));
// Make sure that the method timers haven't been timed yet
assertThat("Method timer counts are incorrect", registry.getTimers(METHOD_TIMERS).values(), everyItem(Matchers.<Timer>hasProperty("count", equalTo(METHOD_COUNT.get()))));
}Example 44
| Project: restfulie-java-master File: FormEncodedTest.java View source code |
@Test
public void shouldConcatenateParams() throws IOException {
FormEncoded encoded = new FormEncoded();
StringWriter writer = new StringWriter();
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Guilherme");
params.put("age", "29");
encoded.marshal(params, writer, new DefaultRestClient());
assertThat(writer.toString(), Matchers.anyOf(is(CoreMatchers.equalTo("name=Guilherme&age=29")), is(CoreMatchers.equalTo("age=29&name=Guilherme"))));
}Example 45
| Project: scm-api-plugin-master File: SCMHeadObserverTest.java View source code |
@Test
public void collect() throws Exception {
SCMHead head1 = new SCMHead("bar");
SCMRevision revision1 = mock(SCMRevision.class);
SCMHead head2 = new SCMHead("foo");
SCMRevision revision2 = mock(SCMRevision.class);
SCMHeadObserver.Collector instance = SCMHeadObserver.collect();
assertThat("Observing from the start", instance.isObserving(), is(true));
assertThat("Wants everything", instance.getIncludes(), nullValue());
instance.observe(head1, revision1);
assertThat("Still observing", instance.isObserving(), is(true));
instance.observe(head2, revision2);
assertThat("Still observing", instance.isObserving(), is(true));
assertThat(instance.result(), Matchers.<Map<SCMHead, SCMRevision>>allOf(hasEntry(head1, revision1), hasEntry(head2, revision2)));
}Example 46
| Project: activityinfo-master File: AsyncFormTreeBuilderTest.java View source code |
@Test
public void treeResolver() {
ResourceLocator locator = new ResourceLocatorAdaptor(getDispatcher());
AsyncFormTreeBuilder treeBuilder = new AsyncFormTreeBuilder(locator);
ResourceId formClassId = CuidAdapter.activityFormClass(1);
FormTree tree = assertResolves(treeBuilder.apply(formClassId));
System.out.println(tree);
assertThat(tree.getRootFormClasses().keySet(), Matchers.hasItems(formClassId));
}Example 47
| Project: beam-master File: HadoopFileSystemModuleTest.java View source code |
@Test
public void testConfigurationSerializationDeserialization() throws Exception {
Configuration baseConfiguration = new Configuration(false);
baseConfiguration.set("testPropertyA", "baseA");
baseConfiguration.set("testPropertyC", "baseC");
Configuration configuration = new Configuration(false);
configuration.addResource(baseConfiguration);
configuration.set("testPropertyA", "A");
configuration.set("testPropertyB", "B");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new HadoopFileSystemModule());
String serializedConfiguration = objectMapper.writeValueAsString(configuration);
Configuration deserializedConfiguration = objectMapper.readValue(serializedConfiguration, Configuration.class);
assertThat(deserializedConfiguration, Matchers.<Map.Entry<String, String>>containsInAnyOrder(new AbstractMap.SimpleEntry("testPropertyA", "A"), new AbstractMap.SimpleEntry("testPropertyB", "B"), new AbstractMap.SimpleEntry("testPropertyC", "baseC")));
}Example 48
| Project: darcy-ui-master File: ElementTextTest.java View source code |
@Test
public void shouldNotMatchDifferentElementText() {
ElementText<Text> matcher = new ElementText<>(Matchers.containsString("some element text"));
Text mockText = mock(Text.class);
when(mockText.isPresent()).thenReturn(true);
when(mockText.getText()).thenReturn("some different element text");
assertFalse(matcher.matches(mockText));
}Example 49
| Project: extended-objects-master File: IndexedDemoTest.java View source code |
@Test
public void test() {
XOManager xoManager = getXoManager();
xoManager.currentTransaction().begin();
Person person1 = xoManager.create(Person.class);
person1.setName("Peter");
xoManager.currentTransaction().commit();
xoManager.currentTransaction().begin();
Person person2 = xoManager.find(Person.class, "Peter").getSingleResult();
Assert.assertThat(person2, Matchers.equalTo(person1));
xoManager.currentTransaction().commit();
}Example 50
| Project: inspectIT-master File: ProfileUpdateJobTest.java View source code |
@Test
public void addedAssignment() throws RemoteException {
Collection<ClassType> types = ImmutableList.of(classTypeOne, classTypeTwo);
doReturn(instrumentationApplier).when(configurationResolver).getInstrumentationApplier(sensorAssignment, environment);
doReturn(types).when(classCacheSearchNarrower).narrowByClassSensorAssignment(classCache, sensorAssignment);
doReturn(types).when(instrumentationService).addInstrumentationPoints(eq(types), eq(agentConfiguration), Matchers.<Collection<IInstrumentationApplier>>any());
doReturn(Collections.singleton(sensorAssignment)).when(event).getAddedSensorAssignments();
job.setProfileUpdateEvent(event);
job.run();
ArgumentCaptor<Collection> captor = ArgumentCaptor.forClass(Collection.class);
verify(instrumentationService, times(1)).addInstrumentationPoints(eq(types), eq(agentConfiguration), captor.capture());
assertThat((Collection<IInstrumentationApplier>) captor.getValue(), hasSize(1));
assertThat(((Collection<IInstrumentationApplier>) captor.getValue()).iterator().next(), is(instrumentationApplier));
ArgumentCaptor<Collection> typeCaptor = ArgumentCaptor.forClass(Collection.class);
verify(instrumentationService).getInstrumentationResults(typeCaptor.capture());
assertThat((Collection<ClassType>) typeCaptor.getValue(), hasItems(classTypeOne, classTypeTwo));
ArgumentCaptor<ClassInstrumentationChangedEvent> eventCaptor = ArgumentCaptor.forClass(ClassInstrumentationChangedEvent.class);
verify(eventPublisher).publishEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getAgentId(), is(equalTo(10L)));
Matcher<InstrumentationDefinition> matcherOne = org.hamcrest.Matchers.<InstrumentationDefinition>hasProperty("className", equalTo("fqnOne"));
Matcher<InstrumentationDefinition> matcherTwo = org.hamcrest.Matchers.<InstrumentationDefinition>hasProperty("className", equalTo("fqnTwo"));
assertThat(eventCaptor.getValue().getInstrumentationDefinitions(), hasItems(matcherOne, matcherTwo));
verifyNoMoreInteractions(instrumentationService, eventPublisher);
verifyZeroInteractions(environment);
}Example 51
| Project: jgroups-aws-master File: PortRangeTest.java View source code |
@Parameters(name = "{0}")
public static Collection<Object[]> parameters() throws UnknownHostException {
return Arrays.asList(new Object[][] { { "range 0", awsPing(7800, 0), matchClusterPorts(7800) }, { "range 1", awsPing(7800, 1), matchClusterPorts(7800, 7801) }, { "range 2", awsPing(7800, 2), matchClusterPorts(7800, 7801, 7802) }, { "different range start", awsPing(7803, 3), matchClusterPorts(7803, 7804, 7805, 7806) }, { "default port and range", awsPingDefaultPortAndRange(), Matchers.hasSize(51) } });
}Example 52
| Project: jmock-library-master File: WarnAboutMultipleThreadsAcceptanceTests.java View source code |
public void testKillsThreadsThatTryToCallMockeryThatIsNotThreadSafe() throws InterruptedException {
Mockery mockery = new Mockery();
final MockedType mock = mockery.mock(MockedType.class, "mock");
mockery.checking(new Expectations() {
{
allowing(mock).doSomething();
}
});
blitzer.blitz(new Runnable() {
public void run() {
mock.doSomething();
}
});
Throwable exception = exceptionsOnBackgroundThreads.take();
assertThat(exception.getMessage(), Matchers.containsString("the Mockery is not thread-safe"));
}Example 53
| Project: mockserver-master File: CaseInsensitiveRegexHashMapTestNottableRemove.java View source code |
@Test
public void shouldRemoveNotMatchingEntry() {
// given
CaseInsensitiveRegexHashMap hashMap = hashMap(new String[] { "keyOne", "keyOneValue" }, new String[] { "keyTwo", "keyTwoValue" }, new String[] { "keyThree", "keyThreeValue" });
// when
assertThat(hashMap.remove(not("key.*")), is(Matchers.nullValue()));
// then
assertThat(hashMap.size(), is(3));
assertThat(hashMap.get("keyOne"), is(string("keyOneValue")));
assertThat(hashMap.get("keyTwo"), is(string("keyTwoValue")));
assertThat(hashMap.get("keyThree"), is(string("keyThreeValue")));
}Example 54
| Project: MULE-master File: PluginResourcesResolverTestCase.java View source code |
@Test
public void resolvePluginResourcesForMulePluginWithoutPluginPropertiesDescriptor() {
PluginUrlClassification mulePluginClassification = newPluginUrlClassification(Collections.<URL>emptyList());
PluginResourcesResolver resolver = new PluginResourcesResolver();
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage(Matchers.contains(MULE_PLUGIN_JSON + " couldn't be found for plugin"));
resolver.resolvePluginResourcesFor(mulePluginClassification);
}Example 55
| Project: overthere-master File: SshTunnelConnectionTest.java View source code |
@Test
public void shouldNotHandOutDuplicatePortsWhenSocketsAlwaysSeemToBeFreeLikeOnWindows() {
SshTunnelConnection.TunnelPortManager tunnelPortManager = new SshTunnelConnection.TunnelPortManager() {
@Override
protected ServerSocket tryBind(int localPort) {
ServerSocket mock = mock(ServerSocket.class);
when(mock.getLocalPort()).thenReturn(localPort);
return mock;
}
};
ServerSocket serverSocket = tunnelPortManager.bindToNextFreePort(1025);
ServerSocket serverSocket2 = tunnelPortManager.bindToNextFreePort(1025);
assertThat(serverSocket.getLocalPort(), Matchers.not(equalTo(serverSocket2.getLocalPort())));
}Example 56
| Project: ovirt-engine-master File: AlternativeValidationTest.java View source code |
private void doTest(List<IValidation> validations, boolean expectedToSucceed) {
//$NON-NLS-1$
String reason = "reason";
//$NON-NLS-1$
ValidationResult validationResult = new AlternativeValidation(reason, validations).validate("abc");
assertThat(validationResult.getSuccess(), is(expectedToSucceed));
if (expectedToSucceed) {
assertThat(validationResult.getReasons(), is(emptyCollectionOf(String.class)));
} else {
assertThat(validationResult.getReasons(), is(Matchers.containsInAnyOrder(reason)));
}
}Example 57
| Project: REST-With-Spring-master File: RootDiscoverabilityRestLiveTest.java View source code |
// tests
// GET
@Test
public final void whenGetIsDoneOnRoot_thenSomeURIAreDiscoverable() {
// When
final Response getOnRootResponse = givenAuthenticated().get(paths.getRootUri());
// Then
final List<String> allURIsDiscoverableFromRoot = HTTPLinkHeaderUtil.extractAllURIs(getOnRootResponse.getHeader(HttpHeaders.LINK));
assertThat(allURIsDiscoverableFromRoot, not(Matchers.<String>empty()));
}Example 58
| Project: Sphinx-master File: SpeechMarkerTest.java View source code |
/**
* Test whether the speech marker is able to handle cases in which an
* DataEndSignal occurs somewhere after a SpeechStartSignal. This is might
* occur if the microphone is stopped while someone is speaking.
*/
@Test
public void testEndWithoutSilence() throws DataProcessingException {
int sampleRate = 1000;
input.add(new DataStartSignal(sampleRate));
input.addAll(createClassifiedSpeech(sampleRate, 2., true));
input.add(new DataEndSignal(-2));
List<Data> results = collectOutput(createDataFilter(false));
assertThat(results, Matchers.hasSize(104));
assertThat(results.get(0), instanceOf(DataStartSignal.class));
assertThat(results.get(1), instanceOf(SpeechStartSignal.class));
assertThat(results.get(102), instanceOf(SpeechEndSignal.class));
assertThat(results.get(103), instanceOf(DataEndSignal.class));
}Example 59
| Project: sphinx4-master File: SpeechMarkerTest.java View source code |
/**
* Test whether the speech marker is able to handle cases in which an
* DataEndSignal occurs somewhere after a SpeechStartSignal. This is might
* occur if the microphone is stopped while someone is speaking.
*/
@Test
public void testEndWithoutSilence() throws DataProcessingException {
int sampleRate = 1000;
input.add(new DataStartSignal(sampleRate));
input.addAll(createClassifiedSpeech(sampleRate, 2., true));
input.add(new DataEndSignal(-2));
List<Data> results = collectOutput(createDataFilter(false));
assertThat(results, Matchers.hasSize(104));
assertThat(results.get(0), instanceOf(DataStartSignal.class));
assertThat(results.get(1), instanceOf(SpeechStartSignal.class));
assertThat(results.get(102), instanceOf(SpeechEndSignal.class));
assertThat(results.get(103), instanceOf(DataEndSignal.class));
}Example 60
| Project: spring-data-book-master File: QuerydslProductRepositoryIntegrationTest.java View source code |
@Test
public void findProductsByQuerydslPredicate() {
Product iPad = repository.findOne(product.name.eq("iPad"));
Predicate tablets = product.description.contains("tablet");
Iterable<Product> result = repository.findAll(tablets);
assertThat(result, is(Matchers.<Product>iterableWithSize(1)));
assertThat(result, hasItem(iPad));
}Example 61
| Project: totallylazy-master File: UrlEncodedMessageTest.java View source code |
@Test
public void canParseToPairs() throws Exception {
List<Pair<String, String>> pairs = UrlEncodedMessage.parse("The+string=%C3%BC%40foo-bar");
assertThat(pairs.size(), NumberMatcher.is(1));
assertThat(pairs.get(0).first(), Matchers.is("The string"));
if (!runningOnAMac()) {
assertThat(pairs.get(0).second(), Matchers.is("ü@foo-bar"));
}
}Example 62
| Project: box-java-sdk-master File: BoxCollectionTest.java View source code |
@Test
@Category(IntegrationTest.class)
public void getCollectionItemsSucceeds() {
BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
String fileName = "[getCollectionItemsSucceeds] Test File.txt";
String fileContent = "Test file";
byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8);
InputStream uploadStream = new ByteArrayInputStream(fileBytes);
BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
BoxCollection favorites = null;
for (BoxCollection.Info info : BoxCollection.getAllCollections(api)) {
if (info.getCollectionType().equals("favorites")) {
favorites = info.getResource();
break;
}
}
assertThat(favorites, is(notNullValue()));
uploadedFile.setCollections(favorites);
assertThat(favorites, hasItem(Matchers.<BoxItem.Info>hasProperty("ID", equalTo(uploadedFile.getID()))));
uploadedFile.delete();
}Example 63
| Project: datacollector-master File: MysqlGtidOffSourceIT.java View source code |
@Ignore
@Test
public void shouldWriteBinLogPosition() throws Exception {
MysqlSourceConfig config = createConfig("root");
MysqlSource source = createMysqlSource(config);
SourceRunner runner = new SourceRunner.Builder(MysqlDSource.class, source).addOutputLane(LANE).build();
runner.runInit();
StageRunner.Output output = runner.runProduce(null, MAX_BATCH_SIZE);
List<Record> records = new ArrayList<>(output.getRecords().get(LANE));
assertThat(records, is(Matchers.<Record>empty()));
// add one more
execute(ds, Arrays.asList("INSERT INTO foo (bar) VALUES (2)", "INSERT INTO foo (bar) VALUES (3)"));
output = runner.runProduce(null, MAX_BATCH_SIZE);
records = new ArrayList<>(output.getRecords().get(LANE));
assertThat(records, hasSize(2));
assertThat(records.get(0).get("/BinLogFilename").getValueAsString(), is(notNullValue()));
long position1 = records.get(0).get("/BinLogPosition").getValueAsLong();
assertThat(records.get(1).get("/BinLogFilename").getValueAsString(), is(notNullValue()));
long position2 = records.get(1).get("/BinLogPosition").getValueAsLong();
assertThat(position2, is(greaterThan(position1)));
assertThat(records.get(0).get("/Offset"), is(notNullValue()));
assertThat(records.get(1).get("/Offset").getValueAsString(), is(output.getNewOffset()));
execute(ds, "TRUNCATE foo");
}Example 64
| Project: dumpling-master File: PidRuntimeFactoryTest.java View source code |
@Test
public void invokeFactory() throws Exception {
disposer.register(TestThread.setupSleepingThreadWithLock());
ThreadDumpRuntime pidRuntime = FACTORY.fromProcess(Util.currentPid());
ThreadDumpThread thread = pidRuntime.getThreads().where(nameIs("sleepingThreadWithLock")).onlyThread();
assertThat(thread.getStatus(), equalTo(ThreadStatus.SLEEPING));
assertThat(thread.getAcquiredLocks(), not(Matchers.<ThreadLock>emptyIterable()));
assertThat(only(thread.getAcquiredLocks()).getClassName(), equalTo("java.util.concurrent.locks.ReentrantLock$NonfairSync"));
}Example 65
| Project: maven-scm-master File: HistoryConsumerTest.java View source code |
@Test
public void testConsumeStreamHistory() throws IOException {
List<Transaction> transactions = new ArrayList<Transaction>();
XppStreamConsumer consumer = new HistoryConsumer(new DefaultLog(), transactions);
AccuRevJUnitUtil.consume("/streamHistory.xml", consumer);
assertThat(transactions.size(), is(4));
Transaction t = transactions.get(0);
assertThat(t.getTranType(), is("promote"));
assertThat(t.getWhen(), is(new Date(1233782838000L)));
assertThat(t.getAuthor(), is("ggardner"));
assertThat(t.getId(), is(50L));
assertThat(t.getVersions().size(), is(2));
assertThat(t.getVersions(), Matchers.<Transaction.Version>hasItem(version(8L, "/./tcktests/src/main/java/Application.java", "1/1", "2/3")));
t = transactions.get(1);
assertThat(t.getComment(), is("hpromoting"));
}Example 66
| Project: mongojack-master File: TestJacksonDBCollection.java View source code |
@Test
public void testRemove() {
coll.insert(new MockObject("ten", 10));
coll.insert(new MockObject("ten", 100));
MockObject object = new MockObject("1", "twenty", 20);
coll.insert(object);
coll.remove(new BasicDBObject("string", "ten"));
List<MockObject> remaining = coll.find().toArray();
assertThat(remaining, Matchers.hasSize(1));
assertThat(remaining, contains(object));
}Example 67
| Project: sync-android-master File: IndexTest.java View source code |
@Test
public void constructsIndexWithDefaultType() {
Index index = new Index(fieldNames, indexName);
assertThat(index.indexName, is("basic"));
assertThat(index.fieldNames, is(Arrays.<FieldSort>asList(new FieldSort("name"), new FieldSort("age"))));
assertThat(index.indexType, Matchers.is(IndexType.JSON));
assertThat(index.tokenizer, is(nullValue()));
}Example 68
| Project: crate-master File: GlobalAggregatePlannerTest.java View source code |
@Test
public void testAggregateOnSubQueryUsesQueryThenFetchIfPossible() throws Exception {
QueryThenFetch plan = e.plan("select sum(x) from (select x, i from t1 order by x limit 10) ti");
List<Projection> projections = ((Collect) plan.subPlan()).collectPhase().projections();
assertThat(projections, Matchers.contains(instanceOf(TopNProjection.class), instanceOf(TopNProjection.class), instanceOf(FetchProjection.class), instanceOf(AggregationProjection.class), instanceOf(EvalProjection.class)));
}Example 69
| Project: cw-omnibus-master File: TILTest.java View source code |
@Test
public void til() {
onView(allOf(withParent(withTILHint("URL")), Matchers.<View>instanceOf(TextInputEditText.class))).perform(typeText(URL), closeSoftKeyboard());
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_CANCELED, null);
intending(hasAction(Intent.ACTION_VIEW)).respondWith(result);
onView(withId(R.id.browse)).perform(click());
intended(allOf(hasAction(Intent.ACTION_VIEW), hasData(URL)));
}Example 70
| Project: geotools-master File: RatioZoomContextTest.java View source code |
@Test
public void testLevels() {
RatioZoomContext ctxt = new RatioZoomContext(5000000, 2);
assertThat(ctxt.getScaleDenominator(0), Matchers.closeTo(5000000, EPSILON));
assertThat(ctxt.getScaleDenominator(1), Matchers.closeTo(5000000 / 2, EPSILON));
assertThat(ctxt.getScaleDenominator(2), Matchers.closeTo(5000000 / 4, EPSILON));
}Example 71
| Project: java-master File: ListAllChannelGroupEndpointTest.java View source code |
@Test
public void testSyncSuccess() throws IOException, PubNubException, InterruptedException {
stubFor(get(urlPathEqualTo("/v1/channel-registration/sub-key/mySubscribeKey/channel-group")).willReturn(aResponse().withBody("{\"status\": 200, \"message\": \"OK\", \"payload\": {\"groups\": [\"a\",\"b\"]}, \"service\": \"ChannelGroups\"}")));
PNChannelGroupsListAllResult response = partialChannelGroup.sync();
assertThat(response.getGroups(), org.hamcrest.Matchers.contains("a", "b"));
}Example 72
| Project: rest-assured-master File: CookieMatcherTest.java View source code |
@Test
public void deals_with_empty_cookie_values() {
// Given
String[] cookiesAsString = new String[] { "un=bob; domain=bob.com; path=/", "", "_session_id=asdfwerwersdfwere; domain=bob.com; path=/; HttpOnly" };
// When
Cookies cookies = CookieMatcher.getCookies(cookiesAsString);
// Then
assertThat(cookies.size(), is(3));
assertThat(cookies, Matchers.<Cookie>hasItem(nullValue()));
}Example 73
| Project: appstatus-master File: ZombieTest.java View source code |
/**
* Ensure running jobs are not deleted by clean operations.
*
* @throws Exception
*/
@Test
public void testIssue1() throws Exception {
Properties p = new Properties();
p.setProperty("batch.zombieInterval", "1000");
AppStatus appStatus = new AppStatus();
appStatus.setConfiguration(p);
appStatus.init();
// Create two finished job.
appStatus.getBatchProgressMonitor("Batch name", "Batch group", UUID.randomUUID().toString());
Assert.assertThat(appStatus.getBatchManager().getRunningBatches().get(0).getStatus(), Matchers.is(IBatch.STATUS_RUNNING));
Thread.sleep(1001);
Assert.assertThat(appStatus.getBatchManager().getRunningBatches().get(0).getStatus(), Matchers.is(IBatch.STATUS_ZOMBIE));
}Example 74
| Project: auth0-java-master File: RulesFilterTest.java View source code |
@Test
public void shouldFilterWithFields() throws Exception {
RulesFilter instance = filter.withFields("a,b,c", true);
assertThat(filter, is(instance));
assertThat(filter.getAsMap(), is(notNullValue()));
assertThat(filter.getAsMap(), Matchers.hasEntry("fields", (Object) "a,b,c"));
assertThat(filter.getAsMap(), Matchers.hasEntry("include_fields", (Object) true));
}Example 75
| Project: cache2k-master File: ClientServerTest.java View source code |
/**
* Ensure that we and send a "ping" and receive a "pong" between a
* {@link Client} and a {@link Server}.
*/
@Test
public void shouldPingPong() {
Server server = new Server(10000);
server.addOperationHandler(new PingPong());
try {
server.open();
Client client = new Client(server.getInetAddress(), server.getPort());
String result = client.invoke(new PingPong());
assertThat(result, Matchers.equalTo("pong"));
} catch (IOException e) {
}
}Example 76
| Project: EspressoExamples-master File: SearchViewTest.java View source code |
public void testSearchSuggestionDisplayed() {
onView(withId(R.id.action_search)).perform(click());
onView(isAssignableFrom(EditText.class)).perform(typeText(HELSINKI), pressImeActionButton());
// Go back to previous screen
pressBack();
// Clear the text in search field
onView(isAssignableFrom(EditText.class)).perform(clearText());
// Enter the first letter of the previously searched word
onView(isAssignableFrom(EditText.class)).perform(typeText("He"));
// Check the search suggestions appear
onView(withText(HELSINKI)).inRoot(withDecorView(not(Matchers.is(getActivity().getWindow().getDecorView())))).check(matches(isDisplayed()));
}Example 77
| Project: haze-master File: OrToInVisitorTest.java View source code |
@Test
public void whenThresholdExceeded_thenRewriteToInPredicate() {
// (age = 1 or age = 2 or age = 3 or age = 4 or age = 5) --> (age in (1, 2, 3, 4, 5))
Predicate p1 = equal("age", 1);
Predicate p2 = equal("age", 2);
Predicate p3 = equal("age", 3);
Predicate p4 = equal("age", 4);
Predicate p5 = equal("age", 5);
OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5);
InPredicate result = (InPredicate) visitor.visit(or, mockIndexes);
Comparable[] values = result.values;
assertThat(values, arrayWithSize(5));
assertThat(values, Matchers.is(Matchers.<Comparable>arrayContainingInAnyOrder(1, 2, 3, 4, 5)));
}Example 78
| Project: hazelcast-master File: OrToInVisitorTest.java View source code |
@Test
public void whenThresholdExceeded_thenRewriteToInPredicate() {
// (age = 1 or age = 2 or age = 3 or age = 4 or age = 5) --> (age in (1, 2, 3, 4, 5))
Predicate p1 = equal("age", 1);
Predicate p2 = equal("age", 2);
Predicate p3 = equal("age", 3);
Predicate p4 = equal("age", 4);
Predicate p5 = equal("age", 5);
OrPredicate or = (OrPredicate) or(p1, p2, p3, p4, p5);
InPredicate result = (InPredicate) visitor.visit(or, mockIndexes);
Comparable[] values = result.values;
assertThat(values, arrayWithSize(5));
assertThat(values, Matchers.is(Matchers.<Comparable>arrayContainingInAnyOrder(1, 2, 3, 4, 5)));
}Example 79
| Project: head-master File: QuestionGroupSectionMatcher.java View source code |
@Override
public boolean matchesSafely(SectionDetail sectionDetail) {
boolean sameTitle = equalsIgnoreCase(this.sectionDetail.getName(), sectionDetail.getName());
if (sameTitle && this.sectionDetail.getQuestions().size() == sectionDetail.getQuestions().size()) {
for (SectionQuestionDetail questionDetail : this.sectionDetail.getQuestions()) {
assertThat(sectionDetail.getQuestions(), Matchers.hasItem(new SectionQuestionDetailMatcher(questionDetail)));
}
}
return sameTitle;
}Example 80
| Project: intellij-community-master File: PyDependenciesComparatorTest.java View source code |
public void test() {
myFixture.configureByFile("/refactoring/dependenciesTest.py");
final PyClass clazz = getClassByName("Foo");
// Can't be null (class has docstring)
@SuppressWarnings("ConstantConditions") PsiElement docStringExpression = clazz.getDocStringExpression().getParent();
PyFunction method = clazz.getMethods()[0];
PsiElement classField = clazz.getClassAttributes().get(0).getParent();
final List<PyStatement> elementList = new ArrayList<>();
elementList.addAll(Arrays.asList(clazz.getStatementList().getStatements()));
Collections.sort(elementList, PyDependenciesComparator.INSTANCE);
Assert.assertThat("Members returned in wrong order", elementList, Matchers.contains(docStringExpression, classField, method));
}Example 81
| Project: jetty.project-master File: SharedBlockingCallbackTest.java View source code |
@Test
public void testDone() throws Exception {
long start;
try (Blocker blocker = sbcb.acquire()) {
blocker.succeeded();
start = System.currentTimeMillis();
blocker.block();
}
Assert.assertThat(System.currentTimeMillis() - start, Matchers.lessThan(500L));
Assert.assertEquals(0, notComplete.get());
}Example 82
| Project: mifos-head-master File: QuestionGroupSectionMatcher.java View source code |
@Override
public boolean matchesSafely(SectionDetail sectionDetail) {
boolean sameTitle = equalsIgnoreCase(this.sectionDetail.getName(), sectionDetail.getName());
if (sameTitle && this.sectionDetail.getQuestions().size() == sectionDetail.getQuestions().size()) {
for (SectionQuestionDetail questionDetail : this.sectionDetail.getQuestions()) {
assertThat(sectionDetail.getQuestions(), Matchers.hasItem(new SectionQuestionDetailMatcher(questionDetail)));
}
}
return sameTitle;
}Example 83
| Project: nuxeo-services-master File: CanTranscodeCharsetsTest.java View source code |
@Test
public void transcodeLatin1() throws IOException, ClientException {
InputStream in = CanTranscodeCharsetsTest.class.getResource("/latin1.txt").openStream();
InputStreamBlob latin1Blob = new InputStreamBlob(in);
latin1Blob.setMimeType("text/plain");
BlobHolder holder = new SimpleBlobHolder(latin1Blob);
UTF8CharsetConverter encoder = new UTF8CharsetConverter();
Blob blob = encoder.convert(holder, null).getBlob();
Assert.assertThat(blob.getMimeType(), Matchers.is("text/plain"));
Assert.assertThat(blob.getEncoding(), Matchers.is("UTF-8"));
String content = blob.getString();
Assert.assertThat(content, Matchers.is("Test de prévisualisation avant rattachement"));
}Example 84
| Project: onos-master File: TwoWayP2PIntentTest.java View source code |
/**
* Checks that the optical path ntent objects are created correctly.
*/
@Test
public void testContents() {
assertThat(intent1.appId(), equalTo(APP_ID));
assertThat(intent1.one(), Matchers.equalTo(connectPoint("one", 1)));
assertThat(intent1.two(), Matchers.equalTo(connectPoint("two", 2)));
assertThat(intent1.priority(), is(PRIORITY));
assertThat(intent1.selector(), is(selector));
assertThat(intent1.treatment(), is(treatment));
}Example 85
| Project: rewrite-master File: NavigateOutcomeTest.java View source code |
@Test
public void testNavigateNoParams() throws Exception {
HtmlPage firstPage = getWebClient("/navigate").getPage();
HtmlPage secondPage = firstPage.getHtmlElementById("form:navigateNoParams").click();
assertThat(secondPage.getWebResponse().getWebRequest().getHttpMethod(), is(HttpMethod.POST));
assertThat(secondPage.getUrl().toString(), Matchers.containsString(getContextPath() + "/navigate"));
}Example 86
| Project: RoboBinding-gallery-master File: DemoTraveller.java View source code |
public void testTravelThroughAllDemos() {
Spinner demoSpinner = (Spinner) getActivity().findViewById(R.id.demoSpinner);
int numDemos = demoSpinner.getCount();
for (int i = 0; i < numDemos; i++) {
Espresso.onData(Matchers.anything()).inAdapterView(ViewMatchers.withId(R.id.demoSpinner)).atPosition(i).perform(ViewActions.click());
Espresso.pressBack();
Espresso.onView(ViewMatchers.withId(R.id.showDemoButton)).perform(ViewActions.click());
Espresso.pressBack();
}
}Example 87
| Project: rxnorm-client-master File: NihInteractionServiceProxyTest.java View source code |
@Test
@Category(ServiceIntegrationTest.class)
public void testFindInteractionsFromList() throws Exception {
InteractionDrugResponse response = proxy.findDrugInteractions("152923");
InteractionTypeGroup interactionGroup = response.getInteractionTypeGroup().get(0);
InteractionType interactionType = interactionGroup.getInteractionType().get(0);
assertThat("RxCUI 152923 has 66 interaction pairs.", interactionType.getInteractionPair().size(), Matchers.is(66));
}Example 88
| Project: spring-integration-master File: ExponentialMovingAverageRatioTests.java View source code |
@Test
@SuppressWarnings("unchecked")
public void testGetTimeSinceLastMeasurement() throws Exception {
long sleepTime = 20L;
// fill history with the same value.
long now = System.nanoTime() - 2 * sleepTime * 1000000;
for (int i = 0; i < TestUtils.getPropertyValue(history, "retention", Integer.class); i++) {
history.success(now);
}
final Deque<Long> times = TestUtils.getPropertyValue(history, "times", Deque.class);
assertEquals(Long.valueOf(now), times.peekFirst());
assertEquals(Long.valueOf(now), times.peekLast());
//increment just so we'll have a different value between first and last
history.success(System.nanoTime() - sleepTime * 1000000);
assertNotEquals(times.peekFirst(), times.peekLast());
/*
* We've called Thread.sleep twice with the same value in quick
* succession. If timeSinceLastSend is pulling off the correct end of
* the queue, then we should be closer to the sleep time than we are to
* 2 x sleepTime, but we should definitely be greater than the sleep
* time.
*/
double timeSinceLastMeasurement = history.getTimeSinceLastMeasurement();
assertThat(timeSinceLastMeasurement, Matchers.greaterThan((double) (sleepTime / 100)));
assertThat(timeSinceLastMeasurement, Matchers.lessThanOrEqualTo(1.5 * sleepTime / 100));
}Example 89
| Project: spring-xd-master File: SynchronizingModuleRegistryTests.java View source code |
@Test
public void deletionViaOneIsReflectedOnTwo_SingleFind() {
UploadedModuleDefinition def = new UploadedModuleDefinition("fizz", processor, "bonjour".getBytes());
synch1.registerNew(def);
ModuleDefinition result = synch2.findDefinition("fizz", processor);
assertThat(result, pointsToContentsThat(equalTo("bonjour")));
synch1.delete(def);
result = synch2.findDefinition("fizz", processor);
assertThat(result, Matchers.nullValue());
}Example 90
| Project: twitterminer-master File: KeywordStatisticsTest.java View source code |
@Test
public void testExtractReturnsMultipleOccurrences() {
//setup
String message = "dfksfdk fjsoijf soidf jdf Poker dsfdkfs dfoi Tournament jsdf oij";
//act
Map<String, Long> result = testObj.extract(message, Lists.newArrayList("Poker", "Tournament"));
//assert
assertNotNull(result);
assertThat(result, Matchers.allOf(hasEntry(is("Poker"), is(1L)), Matchers.hasEntry(is("Tournament"), is(1L))));
}Example 91
| Project: vraptor-vraptor2-master File: VRaptor2ConfigTest.java View source code |
@Test
public void readsConverters() throws IOException, ConfigException {
final File file = create("<converter>myCustomConverter</converter>");
mockery.checking(new Expectations() {
{
one(context).getRealPath("/WEB-INF/classes/vraptor.xml");
will(returnValue(file.getAbsolutePath()));
one(context).getRealPath("/WEB-INF/classes/views.properties");
will(returnValue(new File("unknown").getAbsolutePath()));
}
});
VRaptor2Config config = new VRaptor2Config(context);
assertThat(config.getConverters(), hasItem("myCustomConverter"));
assertThat(config.getConverters(), Matchers.hasSize(1));
mockery.assertIsSatisfied();
}Example 92
| Project: geoserver-master File: WMSLayerTest.java View source code |
@Test
public void testPostAsXML() throws Exception {
assertThat(catalog.getResourceByName("sf", "bugsites", WMSLayerInfo.class), nullValue());
String xml = "<wmsLayer>" + "<name>bugsites</name>" + "<nativeName>world4326</nativeName>" + "<srs>EPSG:4326</srs>" + "<nativeCRS>EPSG:4326</nativeCRS>" + "<store>demo</store>" + "</wmsLayer>";
MockHttpServletResponse response = postAsServletResponse(RestBaseController.ROOT_PATH + "/workspaces/sf/wmsstores/demo/wmslayers/", xml, "text/xml");
assertThat(response, hasStatus(HttpStatus.CREATED));
assertThat(response, hasHeader("Location", Matchers.endsWith("/workspaces/sf/wmsstores/demo/wmslayers/bugsites")));
WMSLayerInfo layer = catalog.getResourceByName("sf", "bugsites", WMSLayerInfo.class);
assertThat(layer, hasProperty("nativeBoundingBox", notNullValue()));
}Example 93
| Project: baigan-config-master File: ConfigurationContextProvisionIT.java View source code |
@Test
public void testProvisioning() {
final String contextParam = ConfigurationContext.APPDOMAIN.name();
final Collection<ContextProvider> contextProviders = retriever.getProvidersFor(contextParam);
assertThat(contextProviders.size(), equalTo(1));
final String contextValue = contextProviders.iterator().next().getContextParam(contextParam);
assertThat(contextValue, Matchers.equalTo("1"));
}Example 94
| Project: ci-eye-master File: JobLaboratoryTest.java View source code |
@Test
public void returnsInstantlyForAGreenJobThatIsNotBuilding() {
context.checking(new Expectations() {
{
allowing(contact).makeJsonRestCall("jobUrl/api/json", JobDetail.class);
will(returnValue(new JobDetail()));
}
});
TargetDetail target = jobLab.analyseJob(job);
assertThat(target.status(), Matchers.is(Status.GREEN));
}Example 95
| Project: deadcode4j-master File: A_PackagingHandler.java View source code |
@Test
public void addsCompileSourceRootsAsCodeRepositories() throws MojoExecutionException, IOException {
MavenProject mavenProject = new MavenProject();
mavenProject.getCompileSourceRoots().add(directoryThisClassIsLocated());
Iterable<Repository> repositories = objectUnderTest.getAdditionalRepositoriesFor(mavenProject);
assertThat(repositories, is(Matchers.<Repository>iterableWithSize(1)));
Repository repository = repositories.iterator().next();
Collection<String> results = getFileNames(repository);
assertThat(results, hasItem(getClass().getSimpleName() + ".java"));
}Example 96
| Project: fluent-reflection-master File: TestReflectionOnInherentedMethods.java View source code |
@Test
public void declaredSubclassMethodsAreFound() {
final List<FluentMethod> methodsDeclaredByExampleSubclass = type(ExampleSubclass.class).methods(declaredBy(ExampleSubclass.class));
assertThat(methodsDeclaredByExampleSubclass, Matchers.<FluentMethod>hasItem(hasName("getSubclassProperty")));
assertThat(methodsDeclaredByExampleSubclass.size(), equalTo(1));
}Example 97
| Project: inproctester-master File: InProcessHtmlUnitDriverTestWithWebXml.java View source code |
@Test
public void shouldSupportCookies() {
WebDriver htmlUnitDriver = new InProcessHtmlUnitDriver(httpAppTester);
htmlUnitDriver.manage().deleteAllCookies();
htmlUnitDriver.get("http://localhost/contacts/add");
htmlUnitDriver.findElement(By.name("contactName")).sendKeys("My Contact");
htmlUnitDriver.findElement(By.tagName("form")).submit();
assertThat(htmlUnitDriver.findElement(By.className("message")).getText(), is("Success"));
htmlUnitDriver.get("http://localhost/contacts/1");
Cookie flashMessageCookie = htmlUnitDriver.manage().getCookieNamed("FLASH_MESSAGE");
assertThat(flashMessageCookie, is(nullValue()));
assertThat(htmlUnitDriver.findElements(By.className("message")), is(Matchers.<WebElement>empty()));
}Example 98
| Project: Iogi-master File: TypeConverterTests.java View source code |
@Test
public void ifAnArbitratyExceptionIsThrownWhileConvertingItWillBeWrappedInAConvertionException() throws Exception {
final ArithmeticException expectedWrappedException = new ArithmeticException();
class MockTypeConverter extends TypeConverter<Fizzble> {
@Override
protected Fizzble convert(final String stringValue, final Target<?> to) {
throw expectedWrappedException;
}
public boolean isAbleToInstantiate(final Target<?> target) {
return false;
}
}
final MockTypeConverter typeConverter = new MockTypeConverter();
try {
typeConverter.instantiate(Target.create(Fizzble.class, "foo"), new Parameters(new Parameter("foo", "oops")));
fail();
} catch (final ConversionException thrownException) {
assertEquals(expectedWrappedException, thrownException.getCause());
final String string = thrownException.getMessage();
assertThat(string, Matchers.<String>both(containsString("Fizzble")).and(containsString("foo")));
}
}Example 99
| Project: OpenESPI-DataCustodian-java-master File: UsagePointTests.java View source code |
@Test
public void getRelatedLinkHrefs() throws Exception {
UsagePoint usagePoint = new UsagePoint();
LinkType link1 = new LinkType();
link1.setHref("href1");
usagePoint.getRelatedLinks().add(link1);
LinkType link2 = new LinkType();
link2.setHref("href2");
usagePoint.getRelatedLinks().add(link2);
List<String> relatedLinkHrefs = usagePoint.getRelatedLinkHrefs();
assertThat(relatedLinkHrefs, allOf(Matchers.hasItem("href1"), Matchers.hasItem("href2")));
}Example 100
| Project: sling-master File: RatingPostServletTest.java View source code |
// @Test
public void successfulSave() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put(RatingsUtil.PROPERTY_RATING, "5");
context.registerService(RatingsService.class, Mockito.mock(RatingsService.class));
RatingPostServlet servlet = context.registerInjectActivateService(new RatingPostServlet());
MockSlingHttpServletRequest request = context.request();
request.setRemoteUser("admin");
request.setParameterMap(params);
request.setResource(context.create().resource(SlingshotConstants.APP_ROOT_PATH + "/content/admin/travel"));
MockSlingHttpServletResponse response = new MockSlingHttpServletResponse();
servlet.doPost(request, response);
assertThat(response.getStatus(), Matchers.equalTo(SC_OK));
String output = response.getOutputAsString();
assertThat(output, equalTo("{ \"rating\" : 0}"));
}Example 101
| Project: spring-cloud-netflix-master File: SpringRetryEnabledTests.java View source code |
@Test
public void testLoadBalancedRetryFactoryBean() throws Exception {
Map<String, LoadBalancedRetryPolicyFactory> factories = context.getBeansOfType(LoadBalancedRetryPolicyFactory.class);
assertThat(factories.values(), hasSize(1));
assertThat(factories.values().toArray()[0], instanceOf(RibbonLoadBalancedRetryPolicyFactory.class));
Map<String, RibbonLoadBalancingHttpClient> clients = context.getBeansOfType(RibbonLoadBalancingHttpClient.class);
assertThat(clients.values(), hasSize(1));
assertThat(clients.values().toArray()[0], instanceOf(RetryableRibbonLoadBalancingHttpClient.class));
Map<String, CachingSpringLoadBalancerFactory> lbFactorys = context.getBeansOfType(CachingSpringLoadBalancerFactory.class);
assertThat(lbFactorys.values(), Matchers.hasSize(1));
FeignLoadBalancer lb = lbFactorys.values().iterator().next().create("foo");
assertThat(lb, instanceOf(RetryableFeignLoadBalancer.class));
}