Java Code Examples for org.hamcrest.core.StringContains

The following examples show how to use org.hamcrest.core.StringContains. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testCustomizedBlockRequestHandler() throws Exception {
    String url = "/error";
    String prefix = "blocked: ";
    WebFluxCallbackManager.setBlockHandler((exchange, t) -> ServerResponse.ok()
        .contentType(MediaType.TEXT_PLAIN)
        .syncBody(prefix + t.getMessage()));

    this.webClient.get()
        .uri(url)
        .exchange()
        .expectStatus().isOk()
        .expectBody(String.class).value(StringContains.containsString(prefix));

    WebFluxCallbackManager.resetBlockHandler();
}
 
Example 2
@Test
public void subsetCommandTest() throws Exception {

  RequestBuilder rb = MockMvcRequestBuilders.get(path).servletPath(path).param("dataset",
      "scanCdmUnitTests/agg/pointFeatureCollection/netCDFbuoydata/BOD001_000_20050627_20051109.nc");

  MvcResult result = this.mockMvc.perform(rb).andExpect(MockMvcResultMatchers.status().is(200))
      .andExpect(MockMvcResultMatchers.content()
          .string(new StringContains(
              "scanCdmUnitTests/agg/pointFeatureCollection/netCDFbuoydata/BOD001_000_20050627_20051109.nc"))) // LOOK
                                                                                                              // not
                                                                                                              // actually
                                                                                                              // testing
                                                                                                              // subset
      .andExpect(MockMvcResultMatchers.content().contentType(expectType)).andReturn();

  System.out.printf("%s%n", result.getResponse().getContentAsString());
}
 
Example 3
Source Project: iaf   Source File: XsltTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigWarnings() throws ConfigurationException, PipeStartException, IOException, PipeRunException {
	ConfigurationWarnings warnings = ConfigurationWarnings.getInstance();
	warnings.clear(); 
	String styleSheetName=  "/Xslt3/orgchart.xslt";
	setStyleSheetName(styleSheetName);
	setXslt2(false);
	pipe.configure();
	for (int i=0;i<warnings.size();i++) {
		System.out.println(i+" "+warnings.get(i));
	}
	assertTrue("Expected at least one config warnings",warnings.size()>0);
	int nextPos=0;//warnings.size()>4?warnings.size()-2:1;
	assertThat(warnings.get(nextPos), StringContains.containsString("configured xsltVersion [1] does not match xslt version [2] declared in stylesheet"));
	assertThat(warnings.get(nextPos), StringContains.containsString(styleSheetName));
}
 
Example 4
Source Project: Sentinel   Source File: SentinelWebFluxIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomizedBlockRequestHandler() throws Exception {
    String url = "/error";
    String prefix = "blocked: ";
    WebFluxCallbackManager.setBlockHandler((exchange, t) -> ServerResponse.ok()
        .contentType(MediaType.TEXT_PLAIN)
        .syncBody(prefix + t.getMessage()));

    this.webClient.get()
        .uri(url)
        .exchange()
        .expectStatus().isOk()
        .expectBody(String.class).value(StringContains.containsString(prefix));

    WebFluxCallbackManager.resetBlockHandler();
}
 
Example 5
Source Project: iaf   Source File: SaxExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void inspectViaSenderAndTransformerException(SenderException e, SAXException originalException, String expectedInSaxExceptionMessage, Locator locator) {
	System.out.println("multiwrapped getMessage() ["+e.getMessage()+"]");
	System.out.println("multiwrapped toString() ["+e.toString()+"]");
	if (locator!=null) {
		String message= e.getMessage();
		assertThat(message, StringContains.containsString(EXPECTED_LOCATION_MESSAGE_PART1));
		int locationInfoPos=message.indexOf(EXPECTED_LOCATION_MESSAGE_PART1);
		String messageTail=message.substring(locationInfoPos+EXPECTED_LOCATION_MESSAGE_PART1.length());
		assertThat("part of message after location info should not contain location info",messageTail, not(StringContains.containsString(EXPECTED_LOCATION_MESSAGE_PART1)));
	}
	//e.printStackTrace();
	Throwable cause = e.getCause();
	assertThat(cause, IsInstanceOf.instanceOf(TransformerException.class));
	TransformerException tCause = (TransformerException)cause;
	inspectViaTransformerException(tCause, originalException, expectedInSaxExceptionMessage, locator);
}
 
Example 6
Source Project: iaf   Source File: SaxExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void inspectSAXException(SAXException e, String expectedInMessage, Locator locator) {
//		System.out.println("SAXException getMessage() ["+e.getMessage()+"]");
//		System.out.println("SAXException toString() ["+e.toString()+"]");
		//e.printStackTrace();
		assertThat("SaxException toString() must show itself",e.toString(),StringContains.containsString(e.getClass().getSimpleName()));
		assertThat("SaxException toString() must only show itself, not also its cause",e.toString(),not(StringContains.containsString("java.io.IOException")));
		if (StringUtils.isNotEmpty(expectedInMessage)) {
			assertThat(e.getMessage(),StringContains.containsString(expectedInMessage));
		}
		assertThat(e,instanceOf(SAXException.class));
		if (locator!=null) {
			assertThat("location info must be shown", e.getMessage(),StringContains.containsString(EXPECTED_LOCATION_MESSAGE_PART));
		}
		Throwable cause2 = e.getCause();
		assertNotNull("SaxException should have proper cause",cause2);
		assertThat(cause2, IsInstanceOf.instanceOf(IOException.class));
		Throwable cause1 = cause2.getCause();
		assertThat(cause1, IsInstanceOf.instanceOf(NullPointerException.class));
		StackTraceElement[] causeTrace=cause1.getStackTrace();
		assertNotNull(causeTrace);
		assertEquals("throwNullPointer", causeTrace[0].getMethodName());
	}
 
Example 7
Source Project: iaf   Source File: FileSystemActorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void fileSystemActorInfoActionTest(boolean fileViaAttribute) throws Exception {
	String filename = "sender" + FILE1;
	String contents = "Tekst om te lezen";
	
	createFile(null, filename, contents);
	waitForActionToFinish();

	actor.setAction("info");
	if (fileViaAttribute) {
		actor.setFilename(filename);
	}
	actor.configure(fileSystem,null,owner);
	actor.open();
	
	Message message= new Message(fileViaAttribute?null:filename);
	ParameterValueList pvl = null;
	String result = (String)actor.doAction(message, pvl, session);
	assertThat(result,StringContains.containsString("<file name=\"senderfile1.txt\""));
	assertThat(result,StringContains.containsString("size=\"17\""));
	assertThat(result,StringContains.containsString("canonicalName="));
	assertThat(result,StringContains.containsString("modificationDate="));
	assertThat(result,StringContains.containsString("modificationTime="));
}
 
Example 8
Source Project: v8-adapter   Source File: V8JavaAdapterTest.java    License: BSD 3-Clause Clear License 6 votes vote down vote up
@Test
public void shouldNotReadFunctionAsJavaObjectWithoutGcExecutor() {
    V8JavaAdapter.injectClass(NativeJsFunctionReader.class, v8);

    final AtomicInteger sumContainer = new AtomicInteger();
    V8JavaAdapter.injectObject("sumContainer", sumContainer, v8);

    final int one = 1;
    final int two = 2;
    final int sum = one + two;

    thrown.expect(V8ScriptExecutionException.class);
    thrown.expectMessage(StringContains.containsString("No signature exists for sumAndAndTryToNotify"));

    v8.executeScript("var x = new NativeJsFunctionReader(); var y = x.sumAndAndTryToNotify(" + one + ", " + two + ", function(sum) { sumContainer.set(sum); } ); y;");

    Assert.assertEquals(sum, sumContainer.get());
}
 
Example 9
Source Project: iaf   Source File: ForEachChildElementPipeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorXpath() throws Exception {
	Exception targetException = new NullPointerException("FakeException");
	pipe.setSender(getElementRenderer(targetException));
	pipe.setElementXPathExpression("/root/sub");
	configurePipe();
	pipe.start();

	try {
		PipeRunResult prr = doPipe(pipe, messageError, session);
		fail("Expected exception to be thrown");
	} catch (Exception e) {
		assertThat(e.getMessage(),StringContains.containsString("(NullPointerException) FakeException"));
		assertCauseChainEndsAtOriginalException(targetException,e);
	}
}
 
Example 10
Source Project: log4j2-elasticsearch   Source File: BasicCredentialsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void throwsWhenBothParamsAreNull() {

    // given
    BasicCredentials.Builder builder = createTestBuilder()
            .withUsername(null)
            .withPassword(null);

    expectedException.expect(ConfigurationException.class);
    expectedException.expectMessage(AnyOf.anyOf(
            StringContains.containsString("username"),
            StringContains.containsString("password"))
    );

    // when
    builder.build();

}
 
Example 11
Source Project: log4j2-elasticsearch   Source File: BasicCredentialsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void throwsWhenBothParamsAreNull() {

    // given
    BasicCredentials.Builder builder = createTestBuilder()
            .withUsername(null)
            .withPassword(null);

    expectedException.expect(ConfigurationException.class);
    expectedException.expectMessage(AnyOf.anyOf(
            StringContains.containsString("username"),
            StringContains.containsString("password"))
    );

    // when
    builder.build();

}
 
Example 12
Source Project: log4j2-elasticsearch   Source File: BasicCredentialsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void throwsWhenBothParamsAreNull() {

    // given
    BasicCredentials.Builder builder = createTestBuilder()
            .withUsername(null)
            .withPassword(null);

    expectedException.expect(ConfigurationException.class);
    expectedException.expectMessage(AnyOf.anyOf(
            StringContains.containsString("username"),
            StringContains.containsString("password"))
    );

    // when
    builder.build();

}
 
Example 13
Source Project: log4j2-elasticsearch   Source File: BasicCredentialsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void throwsWhenBothParamsAreNull() {

    // given
    BasicCredentials.Builder builder = createTestBuilder()
            .withUsername(null)
            .withPassword(null);

    expectedException.expect(ConfigurationException.class);
    expectedException.expectMessage(AnyOf.anyOf(
            StringContains.containsString("username"),
            StringContains.containsString("password"))
    );

    // when
    builder.build();

}
 
Example 14
Source Project: beam   Source File: BeamSideInputLookupJoinRelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
// Do not add a filter like "WHERE o1.order_id=2". By adding that filter, FilterJoinRule may
// convert "LEFT OUTER JOIN" to "INNER JOIN".
public void testLookupTableLeftOuterJoinWithBoundedTableError() throws Exception {
  String sql =
      "SELECT o1.order_id, o2.site_name FROM "
          + " SITE_LKP o2 "
          + " LEFT OUTER JOIN "
          + " ORDER_DETAILS1 o1 "
          + " on "
          + " o1.site_id=o2.site_id ";
  thrown.expect(UnsupportedOperationException.class);
  thrown.expectMessage(StringContains.containsString("OUTER JOIN must be a non Seekable table"));
  PCollection<Row> rows = compilePipeline(sql, pipeline);
  pipeline.run();
}
 
Example 15
Source Project: beam   Source File: BeamSideInputLookupJoinRelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
// Do not add a filter like "WHERE o1.order_id=2". By adding that filter, FilterJoinRule may
// convert "FULL OUTER JOIN" to "LEFT OUTER JOIN", which, in tis case is a valid scenario.
public void testUnboundedTableFullOuterJoinWithLookupTableError() throws Exception {
  String sql =
      "SELECT o1.order_id, o2.site_name FROM "
          + "(select order_id, site_id FROM ORDER_DETAILS "
          + "          GROUP BY order_id, site_id, TUMBLE(order_time, INTERVAL '1' HOUR)) o1 "
          + " FULL OUTER JOIN "
          + " SITE_LKP o2 "
          + " on "
          + " o1.site_id=o2.site_id";
  thrown.expect(UnsupportedOperationException.class);
  thrown.expectMessage(StringContains.containsString("not supported"));
  PCollection<Row> rows = compilePipeline(sql, pipeline);
  pipeline.run();
}
 
Example 16
Source Project: yes-cart   Source File: BrowsingSuiteTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSearchJson() throws Exception {

    reindex();

    final SearchRO search = new SearchRO();
    search.setParameters(Collections.singletonMap("query", Collections.singletonList("BENDER")));
    search.setSortField("sku.code_sort");

    final byte[] body = toJsonBytes(search);

    mockMvc.perform(post("/search")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .locale(locale)
                .content(body))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(content().string(StringContains.containsString("BENDER-ua")))
            .andExpect(content().string(StringContains.containsString("WAREHOUSE_2")))
            .andExpect(content().string(StringContains.containsString("productAvailabilityModel")))
            .andExpect(content().string(StringContains.containsString("skuAvailabilityModel")))
            .andExpect(content().string(StringContains.containsString("skuQuantityModel")))
            .andExpect(header().string("yc", CustomMatchers.isNotBlank()));

}
 
Example 17
Source Project: nakadi   Source File: HilaAT.java    License: MIT License 6 votes vote down vote up
@Test(timeout = 10000)
public void testGetSubscriptionStatWhenDirectAssignment() throws Exception {
    // connect with 1 stream directly requesting the partition
    final TestStreamingClient client = new TestStreamingClient(URL, subscription.getId(), "",
            Optional.empty(),
            Optional.of("{\"partitions\":[" +
                    "{\"event_type\":\"" + eventType.getName() + "\",\"partition\":\"0\"}]}"));
    client.start();
    // wait for rebalance to finish
    waitFor(() -> assertThat(getNumberOfAssignedStreams(subscription.getId()), Matchers.is(1)));

    NakadiTestUtils.getSubscriptionStat(subscription)
            .then()
            .content(new StringContains(JSON_TEST_HELPER.asJsonString(new SubscriptionEventTypeStats(
                    eventType.getName(),
                    Collections.singletonList(new SubscriptionEventTypeStats.Partition(
                            "0",
                            "assigned",
                            0L,
                            null,
                            client.getSessionId(),
                            DIRECT
                    ))))));
}
 
Example 18
Source Project: skywalking   Source File: PatternLoggerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLogFormat() {
    final List<String> strings = Lists.newArrayList();
    PatternLogger logger = new PatternLogger(PatternLoggerTest.class, PATTERN) {
        @Override
        protected void logger(LogLevel level, String message, Throwable e) {
            String r = format(level, message, e);
            strings.add(r);
        }
    };
    NullPointerException exception = new NullPointerException();
    logger.error("hello world", exception);
    logger.error("hello world", null);
    String formatLines = strings.get(0);
    String[] lines = formatLines.split(Constants.LINE_SEPARATOR);
    Assert.assertThat(lines[0], StringContains.containsString("ERROR [testAppFromConfig,,,] [main] PatternLoggerTest:-1 hello world "));
    Assert.assertEquals("java.lang.NullPointerException", lines[1]);
    Assert.assertThat(lines[2], StringContains.containsString("PatternLoggerTest.testLogFormat"));
    Assert.assertEquals(strings.get(1).split(Constants.LINE_SEPARATOR).length, 1);
}
 
Example 19
Source Project: iaf   Source File: Json2XmlValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
	public void testNoNamespaceXml2Json() throws Exception {
		pipe.setName("Response_To_Json");
		pipe.setOutputFormat("json");
		pipe.setSchema("/Validation/NoNamespace/bp.xsd");
//		pipe.setRoot("GetPartiesOnAgreement_Response");
//		pipe.setTargetNamespace("http://nn.nl/XSD/CustomerAdministration/Party/1/GetPartiesOnAgreement/7");
		pipe.setThrowException(true);
		pipe.configure();
		pipe.start();
		
		String input = TestFileUtils.getTestFile("/Validation/NoNamespace/bp-response.xml");
		String expected = TestFileUtils.getTestFile("/Validation/NoNamespace/bp-response-compact.json");
		
		PipeLineSessionBase session = new PipeLineSessionBase();
		try {
			PipeRunResult prr = doPipe(pipe, input,session);
			fail("expected to fail");
		} catch (PipeRunException e) {
			assertThat(e.getMessage(),StringContains.containsString("Cannot find the declaration of element 'BusinessPartner'"));
		}
	}
 
Example 20
@Test
public void executeWithRetries_should_fail_for_exceeded_retries() throws Exception {

	AbstractServiceUnavailableOperationRetrier retrier = new AbstractServiceUnavailableOperationRetrier(SERVICE_UNAVAILABLE_RETRIES) {

		@Override
		public void execute() {
			AmazonServiceException serviceException = new AmazonServiceException("Test message");
			serviceException.setStatusCode(SERVICE_UNAVAILABLE_STATUS_CODE);
			serviceException.setErrorType(AmazonServiceException.ErrorType.Service);
			throw serviceException;
		}
	};

	try {
		retrier.executeWithRetries();
		fail("Number of retries should be exceeded");
	} catch(DataAccessResourceFailureException e) {
		// Our Exception -- ...times
		assertThat(e.getMessage(), StringContains.containsString("times"));
	}
}
 
Example 21
Source Project: servicecomb-toolkit   Source File: ClassMakerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void runWithInvalidMavenProjectPath() throws InterruptedException, TimeoutException, IOException {

  String projectPath =
      testResourceDirectory + File.separator + "projects" + File.separator + "demo-with-invalid-pom" + File.separator;

  try {
    ClassMaker.compile(projectPath);
    Assert.fail("Run 'runWithInvalidMavenProjectPath' failed, expected to occur RuntimeException but not");
  } catch (RuntimeException e) {
    Assert.assertThat(e.getMessage(), StringContains.containsString("Command exec fail"));
    return;
  }
}
 
Example 22
Source Project: vividus   Source File: StringComparisonRuleTests.java    License: Apache License 2.0 5 votes vote down vote up
static Stream<Arguments> dataProvider()
{
    // @formatter:off
    return Stream.of(
        Arguments.of(StringComparisonRule.IS_EQUAL_TO,      IsEqual.class),
        Arguments.of(StringComparisonRule.CONTAINS,         StringContains.class),
        Arguments.of(StringComparisonRule.DOES_NOT_CONTAIN, IsNot.class),
        Arguments.of(StringComparisonRule.MATCHES,          StringRegularExpression.class)
    );
    // @formatter:on
}
 
Example 23
@Test
public void testCustomizedRequestOriginParser() throws Exception {
    String url = "/hello";
    String limitOrigin = "userA";
    final String headerName = "S-User";
    configureRulesFor(url, 0, limitOrigin);

    WebFluxCallbackManager.setRequestOriginParser(exchange -> {
        String origin = exchange.getRequest().getHeaders().getFirst(headerName);
        return origin != null ? origin : "";
    });

    this.webClient.get()
        .uri(url)
        .accept(MediaType.TEXT_PLAIN)
        .header(headerName, "userB")
        .exchange()
        .expectStatus().isOk()
        .expectBody(String.class).isEqualTo(HELLO_STR);
    // This will be blocked.
    this.webClient.get()
        .uri(url)
        .accept(MediaType.TEXT_PLAIN)
        .header(headerName, limitOrigin)
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.TOO_MANY_REQUESTS)
        .expectBody(String.class).value(StringContains.containsString(BLOCK_MSG_PREFIX));
    this.webClient.get()
        .uri(url)
        .accept(MediaType.TEXT_PLAIN)
        .exchange()
        .expectStatus().isOk()
        .expectBody(String.class).isEqualTo(HELLO_STR);

    WebFluxCallbackManager.resetRequestOriginParser();
}
 
Example 24
@Test
public void translateExceptionIfPossible_should_translate_NumberDomainsExceededException_into_DataIntegrityViolationException() {
	NumberDomainsExceededException numberDomainsExceededException = new NumberDomainsExceededException(
			"Invalid domain number");

	DataAccessException dataAccessException = translator
			.translateExceptionIfPossible(numberDomainsExceededException);

	assertThat(dataAccessException, is(instanceOf(DataIntegrityViolationException.class)));

	assertThat(dataAccessException, is(notNullValue()));
	assertThat(dataAccessException.getLocalizedMessage(), StringContains.containsString("Invalid domain number"));
}
 
Example 25
@Ignore("No longer fails - we ignore command=xxxx")
@Test
public void validateCommandTest() throws Exception {

  RequestBuilder rb = MockMvcRequestBuilders.get(path).servletPath(path)
      .param("dataset", "scanCdmUnitTests/agg/pointFeatureCollection/netCDFbuoydata/BOD001_000_20050627_20051109.nc")
      .param("command", "validate");

  MvcResult result = this.mockMvc.perform(rb).andExpect(MockMvcResultMatchers.status().is(400))
      .andExpect(MockMvcResultMatchers.content().string(new StringContains("UnsupportedOperationException")))
      .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)).andReturn();

  System.out.printf("%s%n", result.getResponse().getContentAsString());
}
 
Example 26
@Test
public void showCommandTest() throws Exception {

  RequestBuilder rb = MockMvcRequestBuilders.get(path).servletPath(path);
  MvcResult result = this.mockMvc.perform(rb).andExpect(MockMvcResultMatchers.status().is(200))
      .andExpect(MockMvcResultMatchers.content().string(new StringContains("catalog")))
      .andExpect(MockMvcResultMatchers.content().contentType(expectType)).andReturn();

  System.out.printf("%s%n", result.getResponse().getContentAsString());
}
 
Example 27
Source Project: Sentinel   Source File: SentinelWebFluxIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomizedRequestOriginParser() throws Exception {
    String url = "/hello";
    String limitOrigin = "userA";
    final String headerName = "S-User";
    configureRulesFor(url, 0, limitOrigin);

    WebFluxCallbackManager.setRequestOriginParser(exchange -> {
        String origin = exchange.getRequest().getHeaders().getFirst(headerName);
        return origin != null ? origin : "";
    });

    this.webClient.get()
        .uri(url)
        .accept(MediaType.TEXT_PLAIN)
        .header(headerName, "userB")
        .exchange()
        .expectStatus().isOk()
        .expectBody(String.class).isEqualTo(HELLO_STR);
    // This will be blocked.
    this.webClient.get()
        .uri(url)
        .accept(MediaType.TEXT_PLAIN)
        .header(headerName, limitOrigin)
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.TOO_MANY_REQUESTS)
        .expectBody(String.class).value(StringContains.containsString(BLOCK_MSG_PREFIX));
    this.webClient.get()
        .uri(url)
        .accept(MediaType.TEXT_PLAIN)
        .exchange()
        .expectStatus().isOk()
        .expectBody(String.class).isEqualTo(HELLO_STR);

    WebFluxCallbackManager.resetRequestOriginParser();
}
 
Example 28
Source Project: v8-adapter   Source File: V8JavaAdapterTest.java    License: BSD 3-Clause Clear License 5 votes vote down vote up
@Test
public void shouldNotHandleNotAnnotatedStaticInvocationsNoAutoDetect() {
    V8JavaAdapter.injectClass(FooNoAutoDetect.class, v8);

    thrown.expect(V8ScriptExecutionException.class);
    thrown.expectMessage(StringContains.containsString("FooNoAutoDetect.doStaticNotAnnotated is not a function"));
    v8.executeScript("FooNoAutoDetect.doStaticNotAnnotated();");
}
 
Example 29
Source Project: v8-adapter   Source File: V8JavaAdapterTest.java    License: BSD 3-Clause Clear License 5 votes vote down vote up
@Test
public void shouldThrowIfFunctionalListenerArgumentsIsReleasedAndReInvokedAgain() {
  final int one = 1;
  final int two = 2;
  final int three = 3;
  final int sum = one + two + three;

  thrown.expect(Exception.class);
  thrown.expectMessage(StringContains.containsString("Object released"));

  Assert.assertEquals(sum, v8.executeScript("var x = new Foo(0); var sumCallBack = function(arg1, arg2, arg3) { return arg1 + arg2 + arg3; }; x.reInvokeReleasedListener(sumCallBack, " + one + ", " + two + ", " + three + ");"));
}
 
Example 30
private void assertContentTypeContains(String expected, Header[]
        contentTypes) {
    Assert.assertTrue(contentTypes.length == 1);
    Header contentTypeHeader = contentTypes[0];
    Assert.assertThat(contentTypeHeader.getValue(), StringContains
            .containsString(expected));
}