Java Code Examples for org.junit.jupiter.api.Assertions#fail()

The following examples show how to use org.junit.jupiter.api.Assertions#fail() . 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
Source File: RouterImplTest.java    From nalu with Apache License 2.0 6 votes vote down vote up
/**
 * Method: parse(String route) with one parameter ("/testRoute02/testParameter01/testParameter02")
 */
@Test
void testParseRoute13() {
  RouteResult routeResult = null;
  try {
    routeResult = this.router.parse("/MockShell/testRoute02/testParameter01/testParameter03");
  } catch (RouterException e) {
    Assertions.fail();
  }
  Assertions.assertEquals("/MockShell",
                          routeResult.getShell());
  Assertions.assertEquals("/MockShell/testRoute02/*/*",
                          routeResult.getRoute());
  Assertions.assertEquals("testParameter01",
                          routeResult.getParameterValues()
                                     .get(0));
}
 
Example 2
Source File: CStandardTest.java    From commons-numbers with Apache License 2.0 6 votes vote down vote up
/**
 * Assert the operation on the complex number is odd or even.
 *
 * <pre>
 * Odd : f(z) = -f(-z)
 * Even: f(z) =  f(-z)
 * </pre>
 *
 * <p>The results must be binary equal; the sign of the complex number is first processed
 * using the provided sign specification.
 *
 * @param z the complex number
 * @param operation the operation
 * @param type the type (assumed to be ODD/EVEN)
 * @param sign the sign specification
 */
private static void assertFunctionType(Complex z,
        UnaryOperator<Complex> operation, FunctionType type, UnspecifiedSign sign) {
    final Complex c1 = operation.apply(z);
    Complex c2 = operation.apply(z.negate());
    if (type == FunctionType.ODD) {
        c2 = c2.negate();
    }
    final Complex t1 = sign.removeSign(c1);
    final Complex t2 = sign.removeSign(c2);

    // Test for binary equality
    if (!equals(t1.getReal(), t2.getReal()) ||
        !equals(t1.getImaginary(), t2.getImaginary())) {
        Assertions.fail(
            String.format("%s equality failed (z=%s, -z=%s). Expected: %s but was: %s (Unspecified sign = %s)",
                          type, z, z.negate(), c1, c2, sign));
        new Exception().printStackTrace();
    }
}
 
Example 3
Source File: CommandsTest.java    From java-slack-sdk with MIT License 6 votes vote down vote up
@Test
public void invalidSignature() {
    MutableHttpRequest<String> request = HttpRequest.POST("/slack/events", "");
    request.header("Content-Type", "application/x-www-form-urlencoded");
    String timestamp = "" + (System.currentTimeMillis() / 1000 - 30 * 60);
    request.header(SlackSignature.HeaderNames.X_SLACK_REQUEST_TIMESTAMP, timestamp);
    String signature = signatureGenerator.generate(timestamp, helloBody);
    request.header(SlackSignature.HeaderNames.X_SLACK_SIGNATURE, signature);
    request.body(helloBody);
    try {
        client.toBlocking().exchange(request, String.class);
        Assertions.fail();
    } catch (HttpClientResponseException e) {
        Assertions.assertEquals(401, e.getStatus().getCode());
        Assertions.assertEquals("{\"error\":\"invalid request\"}", e.getResponse().getBody().get());
    }
}
 
Example 4
Source File: CompositeDistributionSummaryTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMeasure() {
  DistributionSummary t = newDistributionSummary();
  t.record(42);
  clock.setWallTime(3712345L);
  for (Measurement m : t.measure()) {
    Assertions.assertEquals(m.timestamp(), 3712345L);
    if (m.id().equals(t.id().withTag(Statistic.count))) {
      Assertions.assertEquals(m.value(), 1.0, 0.1e-12);
    } else if (m.id().equals(t.id().withTag(Statistic.totalAmount))) {
      Assertions.assertEquals(m.value(), 42, 0.1e-12);
    } else {
      Assertions.fail("unexpected id: " + m.id());
    }
  }
}
 
Example 5
Source File: PearListParserTest.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@Test
void parseMissingInfo() {
    final List<String> missingInfoLines = Arrays.asList(
        "Installed packages, channel pear.php.net:",
        "=========================================",
        "Package              Version State",
        "Archive_Tar          1.4.3   stable",
        "Console_Getopt       "
    );

    try {
        pearListParser.parse(missingInfoLines);
        Assertions.fail("Should have thrown an exception");
    } catch (final IntegrationException ignore) {

    }
}
 
Example 6
Source File: ConcatCursorTest.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
private TestResult iterateAndCompare(List<?> result, RecordCursor<?> cc, Integer limit) {
    Integer i = 0;
    byte[] next = null;
    RecordCursorResult<?> nr;
    Boolean hasNext = true;
    Integer count = 0;
    Object rr;

    while (i < limit && hasNext) {
        try {
            nr = cc.onNext().get();
            if ((hasNext = nr.hasNext()) == true) {
                rr = nr.get();
                if (result != null) {
                    assertEquals(result.get(i), rr);
                }
                next = nr.getContinuation().toBytes();
                count++;
            }
        } catch (Exception e) {
            Assertions.fail("onNext() future completed exceptionally.");
        }
        i++;
    }
    return new TestResult(next, count);
}
 
Example 7
Source File: JMSClient.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
public JMSClient(String className, String url) {
    Class<? extends ConnectionFactory> clazz;
    try {
        clazz = (Class<? extends ConnectionFactory>) Class.forName(className);

        factory = clazz.getConstructor(String.class).newInstance(url);
    } catch (Exception e) {
        LOG.error("Unable to create the JMS client classL {}", e.getMessage(), e);
        Assertions.fail(e);
    }
}
 
Example 8
Source File: CameraAddedEventLogicTest.java    From canon-sdk-java with MIT License 5 votes vote down vote up
private void createEvent() {
    try {
        final Method handleMethod = cameraAddedEventLogic().getClass().getDeclaredMethod("handle", CanonEvent.class);
        final EmptyEvent event = new EmptyEvent();
        handleMethod.setAccessible(true);
        handleMethod.invoke(cameraAddedEventLogic(), event);
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        Assertions.fail("Failed reflection", e);
    }
}
 
Example 9
Source File: RollupsTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void aggregateDistributionSummaries() {
  for (int i = 0; i < 10; ++i) {
    registry.distributionSummary("test", "i", "" + i).record(i);
  }
  clock.setWallTime(5000);
  List<Measurement> input = registry.measurements().collect(Collectors.toList());
  List<Measurement> aggr = Rollups.aggregate(this::removeIdxTag, input);
  Assertions.assertEquals(4, aggr.size());

  for (Measurement m : aggr) {
    Id id = registry.createId("test");
    switch (Utils.getTagValue(m.id(), "statistic")) {
      case "count":
        id = id.withTag("atlas.dstype", "rate").withTag(Statistic.count);
        Assertions.assertEquals(id, m.id());
        Assertions.assertEquals(10.0 / 5.0, m.value(), 1e-12);
        break;
      case "totalAmount":
        id = id.withTag("atlas.dstype", "rate").withTag(Statistic.totalAmount);
        Assertions.assertEquals(id, m.id());
        Assertions.assertEquals(45.0 / 5.0, m.value(), 1e-12);
        break;
      case "totalOfSquares":
        id = id.withTag("atlas.dstype", "rate").withTag(Statistic.totalOfSquares);
        Assertions.assertEquals(id, m.id());
        Assertions.assertEquals(285.0 / 5.0, m.value(), 1e-12);
        break;
      case "max":
        id = id.withTag("atlas.dstype", "gauge").withTag(Statistic.max);
        Assertions.assertEquals(id, m.id());
        Assertions.assertEquals(9.0, m.value(), 1e-12);
        break;
      default:
        Assertions.fail("unexpected id: " + m.id());
        break;
    }
  }
}
 
Example 10
Source File: TestCommons.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
protected void expectedException() {
	try {
		Assertions.fail("Expected exception!");
	} catch (AssertionError e) {
		registerError(e);
		throw e;
	}
}
 
Example 11
Source File: RouterImplTest.java    From nalu with Apache License 2.0 5 votes vote down vote up
/**
 * Method: parse(String route) with one parameter ("/testRoute03/testRoute04/testRoute05/testParameter01")
 */
@Test
void testParseRoute11() {
  try {
    this.router.parse("/MockShell/testRoute03/testRoute04/testRoute05/testParameter01");
    Assertions.fail("Expected exception to be thrown");
  } catch (RouterException e) {
    Assertions.assertEquals(e.getMessage(),
                            "no matching route found for route >>/MockShell/testRoute03/testRoute04/testRoute05/testParameter01<< --> Routing aborted!");
  }
}
 
Example 12
Source File: MongodbPanacheMockingTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testPanacheRepositoryMocking() throws Throwable {
    Assertions.assertEquals(0, mockablePersonRepository.count());

    Mockito.when(mockablePersonRepository.count()).thenReturn(23l);
    Assertions.assertEquals(23, mockablePersonRepository.count());

    Mockito.when(mockablePersonRepository.count()).thenReturn(42l);
    Assertions.assertEquals(42, mockablePersonRepository.count());

    Mockito.when(mockablePersonRepository.count()).thenCallRealMethod();
    Assertions.assertEquals(0, mockablePersonRepository.count());

    Mockito.verify(mockablePersonRepository, Mockito.times(4)).count();

    PersonEntity p = new PersonEntity();
    Mockito.when(mockablePersonRepository.findById(12l)).thenReturn(p);
    Assertions.assertSame(p, mockablePersonRepository.findById(12l));
    Assertions.assertNull(mockablePersonRepository.findById(42l));

    Mockito.when(mockablePersonRepository.findById(12l)).thenThrow(new WebApplicationException());
    try {
        mockablePersonRepository.findById(12l);
        Assertions.fail();
    } catch (WebApplicationException x) {
    }

    Mockito.when(mockablePersonRepository.findOrdered()).thenReturn(Collections.emptyList());
    Assertions.assertTrue(mockablePersonRepository.findOrdered().isEmpty());

    Mockito.verify(mockablePersonRepository).findOrdered();
    Mockito.verify(mockablePersonRepository, Mockito.atLeastOnce()).findById(Mockito.any());
    Mockito.verifyNoMoreInteractions(mockablePersonRepository);
}
 
Example 13
Source File: DoubleDistributionSummaryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Disabled
public void testRegister() {
  DoubleDistributionSummary t = newInstance();
  registry.register(t);
  t.record(42.0);
  clock.setWallTime(65000L);
  for (Measurement m : registry.get(t.id()).measure()) {
    Assertions.assertEquals(m.timestamp(), 65000L);
    switch (get(m.id(), "statistic")) {
      case "count":
        Assertions.assertEquals(m.value(), 1.0 / 65.0, 1e-12);
        break;
      case "totalAmount":
        Assertions.assertEquals(m.value(), 42.0 / 65.0, 1e-12);
        break;
      case "totalOfSquares":
        Assertions.assertEquals(m.value(), 42.0 * 42.0 / 65.0, 1e-12);
        break;
      case "max":
        Assertions.assertEquals(m.value(), 42.0, 1e-12);
        break;
      default:
        Assertions.fail("unexpected id: " + m.id());
        break;
    }
  }
}
 
Example 14
Source File: MongodbPanacheMockingTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
@Order(1)
public void testPanacheMocking() {
    PanacheMock.mock(PersonEntity.class);

    Assertions.assertEquals(0, PersonEntity.count());

    Mockito.when(PersonEntity.count()).thenReturn(23l);
    Assertions.assertEquals(23, PersonEntity.count());

    Mockito.when(PersonEntity.count()).thenReturn(42l);
    Assertions.assertEquals(42, PersonEntity.count());

    Mockito.when(PersonEntity.count()).thenCallRealMethod();
    Assertions.assertEquals(0, PersonEntity.count());

    PanacheMock.verify(PersonEntity.class, Mockito.times(4)).count();

    PersonEntity p = new PersonEntity();

    Mockito.when(PersonEntity.findById(12l)).thenReturn(p);
    Assertions.assertSame(p, PersonEntity.findById(12l));
    Assertions.assertNull(PersonEntity.findById(42l));

    Mockito.when(PersonEntity.findById(12l)).thenThrow(new WebApplicationException());
    try {
        PersonEntity.findById(12l);
        Assertions.fail();
    } catch (WebApplicationException x) {
    }

    Mockito.when(PersonEntity.findOrdered()).thenReturn(Collections.emptyList());
    Assertions.assertTrue(PersonEntity.findOrdered().isEmpty());

    PanacheMock.verify(PersonEntity.class).findOrdered();
    PanacheMock.verify(PersonEntity.class, Mockito.atLeastOnce()).findById(Mockito.any());
    PanacheMock.verifyNoMoreInteractions(PersonEntity.class);
}
 
Example 15
Source File: GetAllOptimizationTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * With ID resolver {@link Region#getAll(Collection)} should be called
 */
@SuppressWarnings("unchecked")
@Test
void optimization_getAll() {
  PersonRepository repository = createRepository(builder -> builder);
  repository.find(person.id.is("id1")).fetch();
  // expect some calls to be intercepted
  if (calls.isEmpty()) {
    Assertions.fail("Region.getAll(...) was not called. Check that this optimization is enabled");
  }
  check(calls).hasSize(1);
  check(calls.get(0).method.getName()).isIn("get", "getAll");
  check((Iterable<Object>) calls.get(0).args[0]).hasAll("id1");
  calls.clear();

  repository.find(person.id.in("id1", "id2")).fetch();
  check(calls).hasSize(1);
  check(calls.get(0).method.getName()).is("getAll");
  check((Iterable<Object>) calls.get(0).args[0]).hasAll("id1", "id2");
  calls.clear();

  // negatives should not use getAll
  repository.find(person.id.isNot("id1")).fetch();
  check(calls.isEmpty());

  repository.find(person.id.notIn("id1", "id2")).fetch();
  check(calls.isEmpty());

  // any other composite expression should not trigger getAll
  repository.find(person.id.is("id1").age.is(1)).fetch();
  repository.find(person.age.is(1).id.in(Arrays.asList("id1", "id2"))).fetch();
  check(calls.isEmpty());
}
 
Example 16
Source File: ServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void testSimple(
        String reqLine, String expectedStatusLine, String... expectedHeaders) throws Exception {

    try (Socket socket = new Socket()) {
        socket.setSoTimeout((int) (idleTimeoutMillis * 4));
        socket.connect(server.httpSocketAddress());
        final PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), false);

        outWriter.print(reqLine);
        outWriter.print("\r\n");
        outWriter.print("Connection: close\r\n");
        outWriter.print("Content-Length: 0\r\n");
        outWriter.print("\r\n");
        outWriter.flush();

        final BufferedReader in = new BufferedReader(new InputStreamReader(
                socket.getInputStream(), StandardCharsets.US_ASCII));

        assertThat(in.readLine()).isEqualTo(expectedStatusLine);
        // Read till the end of the connection.
        final List<String> headers = new ArrayList<>();
        for (;;) {
            final String line = in.readLine();
            if (line == null) {
                break;
            }

            // This is not really correct, but just wanna make it as simple as possible.
            headers.add(line);
        }

        for (String expectedHeader : expectedHeaders) {
            if (!headers.contains(expectedHeader)) {
                Assertions.fail("does not contain '" + expectedHeader + "': " + headers);
            }
        }
    }
}
 
Example 17
Source File: SecurityAnnotationMixingTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldNotBeCalled() {
    Assertions.fail();
}
 
Example 18
Source File: DynamodbBrokenEndpointConfigTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void test() {
    // should not be called, deployment exception should happen first.
    Assertions.fail();
}
 
Example 19
Source File: TestFluent.java    From javageci with Apache License 2.0 4 votes vote down vote up
@Test
public void testFluent() throws Exception {
    if (new Geci().source(maven().module("javageci-examples").mainSource()).register(new Fluent()).generate()) {
        Assertions.fail("Fluent modified source code. Please compile again.");
    }
}
 
Example 20
Source File: ErroneousConfigTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldNotStartApplicationIfPathIsASlash() {
    Assertions.fail();
}