Example usage for junit.framework Assert fail

List of usage examples for junit.framework Assert fail

Introduction

In this page you can find the example usage for junit.framework Assert fail.

Prototype

static public void fail(String message) 

Source Link

Document

Fails a test with the given message.

Usage

From source file:com.amazonaws.http.AmazonHttpClientRequestTimeoutTest.java

@Test
public void testResponseNotBufferedForDisabledRequestTimeout() throws IOException, InterruptedException {
    ClientConfiguration config = new ClientConfiguration().withRequestTimeout(0);
    HttpClientFactory httpClientFactory = new HttpClientFactory();
    HttpClient rawHttpClient = spy(httpClientFactory.createHttpClient(config));

    HttpResponseProxy responseProxy = createHttpResponseProxySpy();
    doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class));

    String localhostEndpoint = "http://localhost:0";
    Request<?> request = new EmptyHttpRequest(localhostEndpoint, HttpMethodName.GET);

    AmazonHttpClient httpClient = new AmazonHttpClient(config, rawHttpClient, null);

    try {//from w  ww .  j av a 2s.  c o m
        httpClient.execute(request, new NullResponseHandler(), new NullErrorResponseHandler(),
                new ExecutionContext());
        Assert.fail("Should have been unable to unmarshall the response!");
    } catch (AmazonClientException e) {
    }

    /* Verify the response is not buffered when the request timeout is disabled. */
    verify(responseProxy, never()).setEntity(any(BufferedHttpEntity.class));
    httpClient.shutdown();
}

From source file:com.mnxfst.testing.server.cfg.TestPTestServerConfigurationParser.java

@Test
public void testEvaluateNodeListWithNullExpressionInput() throws ParserConfigurationException {
    try {/* w w w . j  a va 2 s.  com*/
        PTestServerConfigurationParser p = new PTestServerConfigurationParser();
        p.evaluateNodeList(null, DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        Assert.fail("Expression null and document not null");
    } catch (XPathExpressionException e) {
    }
}

From source file:BQJDBC.QueryResultTest.BQResultSetFunctionTest.java

/**
 * For testing isValid() , Close() , isClosed()
 *///from   w  w  w .j  av  a 2s .  c  om
@Test
public void isClosedValidtest() {
    try {
        Assert.assertEquals(true, BQResultSetFunctionTest.con.isValid(0));
    } catch (SQLException e) {
        Assert.fail("Got an exception" + e.toString());
        e.printStackTrace();
    }
    try {
        Assert.assertEquals(true, BQResultSetFunctionTest.con.isValid(10));
    } catch (SQLException e) {
        Assert.fail("Got an exception" + e.toString());
        e.printStackTrace();
    }
    try {
        BQResultSetFunctionTest.con.isValid(-10);
    } catch (SQLException e) {
        Assert.assertTrue(true);
        // e.printStackTrace();
    }

    try {
        BQResultSetFunctionTest.con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    try {
        Assert.assertTrue(BQResultSetFunctionTest.con.isClosed());
    } catch (SQLException e1) {
        e1.printStackTrace();
    }

    try {
        BQResultSetFunctionTest.con.isValid(0);
    } catch (SQLException e) {
        Assert.assertTrue(true);
        e.printStackTrace();
    }

}

From source file:eu.cloud4soa.soa.git.GitProxyTest.java

@Test
public void testDeletePublicKeyForUser() {

    User user = new User();
    user.setId(new Long(0));
    user.setFullname("Test");
    user.setUriID(userInstanceUriId);//from   ww  w. jav  a  2s.c om
    user.setUsername("testUsername");
    List<Object> arrayList = new ArrayList<Object>();
    arrayList.add(user);
    when(userdao.findBy("uriID", userInstanceUriId)).thenReturn(arrayList);

    String rsa_pub_key = "aabbcc";
    when(pubkeydao.findByUserAndPubkey(user, rsa_pub_key)).thenReturn(new ArrayList<PubKey>());

    String[] array = gitservices.registerPublicKeyForUser(userInstanceUriId, rsa_pub_key);
    Assert.assertEquals("0", array[0]);
    Assert.assertEquals("OK", array[1]);

    ArrayList<PubKey> arrayList1 = new ArrayList<PubKey>();
    PubKey pubKey = new PubKey();
    pubKey.setId(new Long(0));
    arrayList1.add(pubKey);
    when(pubkeydao.findByPubkey(rsa_pub_key)).thenReturn(arrayList1);

    when(userdao.findBy("uriID", userInstanceUriId)).thenReturn(arrayList);
    when(pubkeydao.findByUserAndPubkey(user, rsa_pub_key)).thenReturn(arrayList1);
    array = gitservices.deletePublicKeyFromUser(userInstanceUriId, rsa_pub_key);
    Assert.assertEquals("0", array[0]);
    Assert.assertEquals("OK", array[1]);
    try {
        String originalContent = FileUtils.readFileToString(new File(originalAuthFile));
        String contentModified = FileUtils.readFileToString(authTempFile);
        int compareResult = originalContent.compareTo(contentModified);
        logger.info("Compare:" + compareResult);
        Assert.assertNotSame("File contents are different!", 0, compareResult);
    } catch (IOException ex) {
        logger.error("Error in reading the file: " + ex.getMessage());
        Assert.fail("Error in reading the file: " + ex.getMessage());
    }
}

From source file:org.jboss.shrinkwrap.mobicents.servlet.sip.test.MobicentsSipServletsDeploymentIntegrationUnitTestCase.java

/**
 * Tests that we can execute an HTTP request on a Converged SIP Servlets application
 * and it's fulfilled as expected by returning the SIP application name in addition
 * to the echo value, proving our deployment succeeded
 *//* w  w w . j a  va2s.c  o  m*/
@Test
public void requestWebapp() throws Exception {
    // Get an HTTP Client
    final HttpClient client = new DefaultHttpClient();

    // Make an HTTP Request, adding in a custom parameter which should be echoed back to us
    final String echoValue = "ShrinkWrap>Tomcat Integration";
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("to", PATH_ECHO_SERVLET));
    params.add(new BasicNameValuePair("echo", echoValue));
    final URI uri = URIUtils.createURI("http", BIND_HOST, HTTP_BIND_PORT,
            NAME_SIPAPP + SEPARATOR + servletClass.getSimpleName(), URLEncodedUtils.format(params, "UTF-8"),
            null);
    final HttpGet request = new HttpGet(uri);

    // Execute the request
    log.info("Executing request to: " + request.getURI());
    final HttpResponse response = client.execute(request);
    System.out.println(response.getStatusLine());
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        Assert.fail("Request returned no entity");
    }

    // Read the result, ensure it's what we're expecting (should be the value of request param "echo")
    final BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    final String line = reader.readLine();
    Assert.assertEquals("Unexpected response from Servlet", echoValue + NAME_SIPAPP, line);

}

From source file:at.tugraz.ist.akm.test.webservice.server.SimpleWebServerTest.java

License:asdf

public void testSimpleFileRequest() {
    try {/*from w  w w.j  a  v a 2s.co m*/
        startServer(true);
        logDebug("testSimpleFileRequest");
        HttpPost httppost = newFileHttpPost();
        httppost.setHeader("Accept", "application/text");
        httppost.setHeader("Content-type", "application/text");

        HttpResponse response = mHttpClient.execute(httppost);
        stopServer();
        mWebserver.close();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        response.getEntity().writeTo(baos);

        FileReader reader = new FileReader(mContext, "web/index.html");
        Assert.assertEquals(reader.read(), new String(baos.toByteArray(), DEFAULT_ENCODING));
        reader.close();
        reader = null;
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}

From source file:eu.stratosphere.pact.runtime.task.MatchTaskTest.java

@Test
public void testSortBoth3MatchTask() {

    int keyCnt1 = 20;
    int valCnt1 = 1;

    int keyCnt2 = 20;
    int valCnt2 = 20;

    super.initEnvironment(6 * 1024 * 1024);
    super.addInput(new UniformPactRecordGenerator(keyCnt1, valCnt1, false), 1);
    super.addInput(new UniformPactRecordGenerator(keyCnt2, valCnt2, false), 2);
    super.addOutput(this.outList);

    MatchTask<PactRecord, PactRecord, PactRecord> testTask = new MatchTask<PactRecord, PactRecord, PactRecord>();
    super.getTaskConfig().setLocalStrategy(LocalStrategy.SORT_BOTH_MERGE);
    super.getTaskConfig().setMemorySize(6 * 1024 * 1024);
    super.getTaskConfig().setNumFilehandles(4);

    final int[] keyPos1 = new int[] { 0 };
    final int[] keyPos2 = new int[] { 0 };
    @SuppressWarnings("unchecked")
    final Class<? extends Key>[] keyClasses = (Class<? extends Key>[]) new Class[] { PactInteger.class };

    PactRecordComparatorFactory.writeComparatorSetupToConfig(super.getTaskConfig().getConfiguration(),
            super.getTaskConfig().getPrefixForInputParameters(0), keyPos1, keyClasses);
    PactRecordComparatorFactory.writeComparatorSetupToConfig(super.getTaskConfig().getConfiguration(),
            super.getTaskConfig().getPrefixForInputParameters(1), keyPos2, keyClasses);

    super.registerTask(testTask, MockMatchStub.class);

    try {/*from www.j  av  a  2s  .c o  m*/
        testTask.invoke();
    } catch (Exception e) {
        LOG.debug(e);
        Assert.fail("Invoke method caused exception.");
    }

    int expCnt = valCnt1 * valCnt2 * Math.min(keyCnt1, keyCnt2);

    Assert.assertTrue("Resultset size was " + this.outList.size() + ". Expected was " + expCnt,
            this.outList.size() == expCnt);

    this.outList.clear();

}

From source file:$.CrmTest.java

/**
     * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
     * the add_customer.xml file to add a new customer to the system.
     * <p/>/*from   w ww. j  a  v  a2 s .com*/
     * On the server side, it matches the CustomerService's addCustomer() method
     *
     * @throws Exception
     */
    @Test
    public void postCustomerTest() throws IOException {
        LOG.info("Sent HTTP POST request to add customer");
        String inputFile = this.getClass().getResource("/add_customer.xml").getFile();
        File input = new File(inputFile);
        PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
        post.addRequestHeader("Accept", "application/xml");
        RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
        post.setRequestEntity(entity);
        HttpClient httpclient = new HttpClient();
        String res = "";

        try {
            int result = httpclient.executeMethod(post);
            LOG.info("Response status code: " + result);
            LOG.info("Response body: ");
            res = post.getResponseBodyAsString();
            LOG.info(res);
        } catch (IOException e) {
            LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
            LOG.error(
                    "You should build the 'cxf-cdi' quick start and deploy it to a local Fabric8 before running this test");
            LOG.error("Please read the README.md file in 'cxf-cdi' quick start root");
            Assert.fail("Connection error");
        } finally {
            // Release current connection to the connection pool once you are
            // done
            post.releaseConnection();
        }
        Assert.assertTrue(res.contains("Jack"));

    }

From source file:com.imaginary.home.cloud.CloudTest.java

private void setupUser() throws Exception {
    HashMap<String, Object> user = new HashMap<String, Object>();
    long key = (System.currentTimeMillis() % 100000);

    user.put("firstName", "Test " + key);
    user.put("lastName", "User");
    user.put("email", "test" + key + "@example.com");
    user.put("password", "ABC" + random.nextInt(1000000));

    HttpClient client = getClient();/*from  w ww. ja v a2s .  co  m*/

    HttpPost method = new HttpPost(cloudAPI + "/user");
    long timestamp = System.currentTimeMillis();

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));

    //noinspection deprecation
    method.setEntity(new StringEntity((new JSONObject(user)).toString(), "application/json", "UTF-8"));

    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() == HttpServletResponse.SC_CREATED) {
        String json = EntityUtils.toString(response.getEntity());
        JSONObject u = new JSONObject(json);

        JSONObject keys = (u.has("apiKeys") && !u.isNull("apiKeys")) ? u.getJSONObject("apiKeys") : null;

        if (keys != null) {
            CloudTest.apiKeyId = (keys.has("apiKeyId") && !keys.isNull("apiKeyId")) ? keys.getString("apiKeyId")
                    : null;
            CloudTest.apiKeySecret = (keys.has("apiKeySecret") && !keys.isNull("apiKeySecret"))
                    ? keys.getString("apiKeySecret")
                    : null;
        }
    } else {
        Assert.fail("Failed to create user (" + status.getStatusCode() + ": "
                + EntityUtils.toString(response.getEntity()));
    }
}

From source file:org.atemsource.atem.utility.compare.OrderableCollectionComparatorTest.java

@Test
public void testMovalAndChangedWithId() {

    // we change one entity and move another one. The result is that the changed element is considered to be added and removed.
    EntityA a1 = createEntityA();/*ww w.ja va2 s.c  o m*/
    EntityB b1 = createEntityB();
    EntityA a2 = createEntityA();
    EntityB b2 = createEntityB();
    EntityB b3 = createEntityB();
    EntityB b4 = createEntityB();
    b1.setInteger(1);
    b1.setId("1");
    b2.setInteger(5);
    b2.setId("2");
    b3.setInteger(2);
    b3.setId("1");
    b4.setInteger(5);
    b4.setId("2");
    a2.getList().add(b2);
    a2.getList().add(b1);
    a1.getList().add(b3);
    a1.getList().add(b4);

    Set<Difference> differences = comparisonAssociativeId.getDifferences(a1, a2);

    Assert.assertEquals(3, differences.size());
    for (Difference difference : differences) {
        if (difference instanceof AttributeChange) {
            Assert.assertEquals("list.1.integer", ((AttributeChange) difference).getPath().toString());
        } else if (difference instanceof Rearrangement) {
        } else {
            Assert.fail("we expect a change and two rearrangements");
        }
    }
}