Example usage for junit.framework Assert assertNull

List of usage examples for junit.framework Assert assertNull

Introduction

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

Prototype

static public void assertNull(String message, Object object) 

Source Link

Document

Asserts that an object is null.

Usage

From source file:com.espertech.esper.regression.support.ResultAssertExecution.java

private void assertStep(String timeInSec, int step, Map<Integer, StepDesc> stepAssertions, String[] fields,
        boolean isAssert, boolean isExpectNullRemoveStream) {

    if (preformatlog.isDebugEnabled()) {
        if (listener.isInvoked()) {
            UniformPair<String[]> received = renderReceived(fields);
            String[] newRows = received.getFirst();
            String[] oldRows = received.getSecond();
            int numMaxRows = (newRows.length > oldRows.length) ? newRows.length : oldRows.length;
            for (int i = 0; i < numMaxRows; i++) {
                String newRow = (newRows.length > i) ? newRows[i] : "";
                String oldRow = (oldRows.length > i) ? oldRows[i] : "";
                preformatlog.debug(String.format("%48s %-18s %-20s", "", newRow, oldRow));
            }//from  www . j  a  v  a  2 s .co  m
            if (numMaxRows == 0) {
                preformatlog.debug(String.format("%48s %-18s %-20s", "", "(empty result)", "(empty result)"));
            }
        }
    }

    if (!isAssert) {
        listener.reset();
        return;
    }

    StepDesc stepDesc = null;
    if (stepAssertions != null) {
        stepDesc = stepAssertions.get(step);
    }

    // If there is no assertion, there should be no event received
    if (stepDesc == null) {
        Assert.assertFalse("At time " + timeInSec + " expected no events but received one or more",
                listener.isInvoked());
    } else {
        // If we do expect remove stream events, asset both
        if (!isExpectNullRemoveStream) {
            String message = "At time " + timeInSec;
            Assert.assertTrue(message + " expected events but received none", listener.isInvoked());
            EPAssertionUtil.assertPropsPerRow(listener.getLastNewData(), expected.getProperties(),
                    stepDesc.getNewDataPerRow(), "newData");

            EPAssertionUtil.assertPropsPerRow(listener.getLastOldData(), expected.getProperties(),
                    stepDesc.getOldDataPerRow(), "oldData");
        }
        // If we don't expect remove stream events (istream only), then asset new data only if there
        else {
            // If we do expect new data, assert
            if (stepDesc.getNewDataPerRow() != null) {
                Assert.assertTrue("At time " + timeInSec + " expected events but received none",
                        listener.isInvoked());
                EPAssertionUtil.assertPropsPerRow(listener.getLastNewData(), expected.getProperties(),
                        stepDesc.getNewDataPerRow(), "newData");
            } else {
                // If we don't expect new data, make sure its null
                Assert.assertNull(
                        "At time " + timeInSec + " expected no insert stream events but received some",
                        listener.getLastNewData());
            }

            Assert.assertNull("At time " + timeInSec
                    + " expected no remove stream events but received some(check irstream/istream(default) test case)",
                    listener.getLastOldData());
        }
    }
    listener.reset();
}

From source file:cz.PA165.vozovyPark.dao.ServiceIntervalDAOTest.java

/**
 *
 *///from   w  w  w  . j a v  a2 s . c om
@Test
public void testValidRemove() {
    try {
        Vehicle mercedes = ServiceIntervalDAOTest.getVehicle("Mercedes", 14000, "R4 Diesel", "A",
                UserClassEnum.PRESIDENT, "2f-4xxi-121245", 2009);
        this.vehicleDao.createVehicle(mercedes);
        ServiceInterval interval1 = ServiceIntervalDAOTest.getServiceInterval(new ArrayList<Date>(),
                "Prehodeni koles", 7, mercedes);
        this.serviceIntervalDAO.createSI(interval1);
        ServiceInterval loaded = serviceIntervalDAO.getById(interval1.getId());
        Assert.assertNotNull("Service interval was not created", loaded);

        em.getTransaction().begin();
        serviceIntervalDAO.removeSI(interval1);
        em.getTransaction().commit();

        loaded = serviceIntervalDAO.getById(interval1.getId());
        if (loaded != null) {
            Assert.fail("Interval was not deleted from database.");
        }
        Assert.assertNull("Service interval was not deleted from database", loaded);
    } catch (Exception ex) {
        Assert.fail("Unexpected exception was throwed: " + ex + " " + ex.getMessage());
    }
}

From source file:org.codehaus.modello.generator.jackson.JacksonVerifier.java

public void assertScm(Scm expected, Object actualObject) {
    if (expected == null) {
        Assert.assertNull("/model/scm", actualObject);
    } else {//from w  w  w  .j a  va  2  s  .c  o  m
        Assert.assertNotNull("/model/scm", actualObject);

        Assert.assertEquals("/model/scm", Scm.class, actualObject.getClass());

        Scm actual = (Scm) actualObject;

        Assert.assertEquals("/model/scm/connection", expected.getConnection(), actual.getConnection());

        Assert.assertEquals("/model/scm/developerConnection", expected.getDeveloperConnection(),
                actual.getDeveloperConnection());

        Assert.assertEquals("/model/scm/url", expected.getUrl(), actual.getUrl());
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestReaper.java

private void testSimulationWithLocks(String namespace) throws Exception {
    final int LOCK_CLIENTS = 10;
    final int ITERATIONS = 250;
    final int MAX_WAIT_MS = 10;

    ExecutorService service = Executors.newFixedThreadPool(LOCK_CLIENTS);
    ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<Object>(service);

    Timing timing = new Timing();
    Reaper reaper = null;/*from w w w.j a  va  2s .  c o m*/
    final CuratorFramework client = makeClient(timing, namespace);
    try {
        client.start();

        reaper = new Reaper(client, MAX_WAIT_MS / 2);
        reaper.start();
        reaper.addPath("/a/b");

        for (int i = 0; i < LOCK_CLIENTS; ++i) {
            completionService.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    final InterProcessMutex lock = new InterProcessMutex(client, "/a/b");
                    for (int i = 0; i < ITERATIONS; ++i) {
                        lock.acquire();
                        try {
                            Thread.sleep((int) (Math.random() * MAX_WAIT_MS));
                        } finally {
                            lock.release();
                        }
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < LOCK_CLIENTS; ++i) {
            completionService.take().get();
        }

        Thread.sleep(timing.session());
        timing.sleepABit();

        Stat stat = client.checkExists().forPath("/a/b");
        Assert.assertNull("Child qty: " + ((stat != null) ? stat.getNumChildren() : 0), stat);
    } finally {
        service.shutdownNow();
        IOUtils.closeQuietly(reaper);
        IOUtils.closeQuietly(client);
    }
}

From source file:org.codehaus.modello.generator.jackson.JacksonVerifier.java

public void assertBuild(Build expected, Object actualObject) {
    if (expected == null) {
        Assert.assertNull("/model/builder", actualObject);
    } else {/*w w  w. j  av a 2  s.  co m*/
        Assert.assertNotNull("/model/builder", actualObject);

        Assert.assertEquals("/model/builder", Build.class, actualObject.getClass());

        Build actual = (Build) actualObject;

        Assert.assertEquals("/model/builder/sourceDirectory", expected.getSourceDirectory(),
                actual.getSourceDirectory());

        Assert.assertEquals("/model/builder/unitTestSourceDirectory", expected.getUnitTestSourceDirectory(),
                actual.getUnitTestSourceDirectory());
    }
}

From source file:org.codehaus.modello.generator.jackson.JacksonVerifier.java

public void assertLocal(Local expected, Object actualObject) {
    if (expected == null) {
        Assert.assertNull("/model/local", actualObject);
    } else {//from   w ww  . j  av a  2s . c  om
        Assert.assertNotNull("/model/local", actualObject);

        Assert.assertEquals("/model/local", Local.class, actualObject.getClass());

        Local actual = (Local) actualObject;

        Assert.assertEquals("/model/local/online", expected.isOnline(), actual.isOnline());
    }
}

From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java

protected void validate(HttpServlet servlet, Integer expectedMaxAgeInSeconds, int expectedResponseStatusCode)
        throws Exception {
    // SETUP//from  ww  w . jav a2 s .  com
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter("ExpiresDefault", "access plus 1 minute");
    filterConfig.addInitParameter("ExpiresByType text/xml; charset=utf-8", "access plus 3 minutes");
    filterConfig.addInitParameter("ExpiresByType text/xml", "access plus 5 minutes");
    filterConfig.addInitParameter("ExpiresByType text", "access plus 7 minutes");
    filterConfig.addInitParameter("ExpiresExcludedResponseStatusCodes", "304, 503");

    ExpiresFilter expiresFilter = new ExpiresFilter();
    expiresFilter.init(filterConfig);

    context.addFilter(new FilterHolder(expiresFilter), "/*", Handler.REQUEST);

    context.addServlet(new ServletHolder(servlet), "/test");

    server.start();
    try {
        Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        long timeBeforeInMillis = System.currentTimeMillis();

        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();

        // VALIDATE
        Assert.assertEquals(expectedResponseStatusCode, httpURLConnection.getResponseCode());

        for (Entry<String, List<String>> field : httpURLConnection.getHeaderFields().entrySet()) {
            System.out.println(field.getKey() + ": "
                    + StringUtils.arrayToDelimitedString(field.getValue().toArray(), ", "));
        }

        Integer actualMaxAgeInSeconds;

        String cacheControlHeader = httpURLConnection.getHeaderField("Cache-Control");
        if (cacheControlHeader == null) {
            actualMaxAgeInSeconds = null;
        } else {
            actualMaxAgeInSeconds = null;
            // System.out.println("Evaluate Cache-Control:" +
            // cacheControlHeader);
            StringTokenizer cacheControlTokenizer = new StringTokenizer(cacheControlHeader, ",");
            while (cacheControlTokenizer.hasMoreTokens() && actualMaxAgeInSeconds == null) {
                String cacheDirective = cacheControlTokenizer.nextToken();
                // System.out.println("\tEvaluate directive: " +
                // cacheDirective);
                StringTokenizer cacheDirectiveTokenizer = new StringTokenizer(cacheDirective, "=");
                // System.out.println("countTokens=" +
                // cacheDirectiveTokenizer.countTokens());
                if (cacheDirectiveTokenizer.countTokens() == 2) {
                    String key = cacheDirectiveTokenizer.nextToken().trim();
                    String value = cacheDirectiveTokenizer.nextToken().trim();
                    if (key.equalsIgnoreCase("max-age")) {
                        actualMaxAgeInSeconds = Integer.parseInt(value);
                    }
                }
            }
        }

        if (expectedMaxAgeInSeconds == null) {
            Assert.assertNull("actualMaxAgeInSeconds '" + actualMaxAgeInSeconds + "' should be null",
                    actualMaxAgeInSeconds);
            return;
        }

        Assert.assertNotNull(actualMaxAgeInSeconds);

        int deltaInSeconds = Math.abs(actualMaxAgeInSeconds - expectedMaxAgeInSeconds);
        Assert.assertTrue("actualMaxAgeInSeconds: " + actualMaxAgeInSeconds + ", expectedMaxAgeInSeconds: "
                + expectedMaxAgeInSeconds + ", request time: " + timeBeforeInMillis + " for content type "
                + httpURLConnection.getContentType(), deltaInSeconds < 2000);

    } finally {
        server.stop();
    }
}

From source file:com.espertech.esper.support.util.ArrayAssertionUtil.java

/**
 * Compare the event properties returned by the events of the iterator with the supplied values.
 * @param iterator supplies events// w ww.jav  a  2  s .co  m
 * @param expectedValues is the expected values
 */
public static void assertEqualsExactOrder(Iterator<EventBean> iterator, String[] fields,
        Object[][] expectedValues) {
    ArrayList<Object[]> rows = new ArrayList<Object[]>();
    while (iterator.hasNext()) {
        EventBean event = iterator.next();
        Object[] eventProps = new Object[fields.length];
        for (int i = 0; i < fields.length; i++) {
            eventProps[i] = event.get(fields[i]);
        }
        rows.add(eventProps);
    }

    try {
        iterator.next();
        TestCase.fail();
    } catch (NoSuchElementException ex) {
        // Expected exception - next called after hasNext returned false, for testing
    }

    if (rows.size() == 0) {
        Assert.assertNull("Expected rows in result but received none", expectedValues);
        return;
    }

    Object[][] data = rows.toArray(new Object[0][]);
    if ((expectedValues == null) && (data != null)) {
        Assert.fail("Expected no values but received data: " + data.length + " elements");
    }

    Assert.assertEquals(expectedValues.length, data.length);
    for (int i = 0; i < data.length; i++) {
        assertEqualsExactOrder(data[i], expectedValues[i]);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceTableTests.java

public void testUpdateShouldThrowExceptionIfEntityHasNoValidId() throws Throwable {

    // Object to update
    final PersonTestObject person = new PersonTestObject("John", "Doe", 29);
    person.setId(0);/*ww w  .jav  a  2 s .  c  o  m*/

    String tableName = "MyTableName";
    MobileServiceClient client = null;

    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Get the MobileService table
    MobileServiceTable<PersonTestObject> msTable = client.getTable(tableName, PersonTestObject.class);

    // Call the update method

    PersonTestObject p = null;
    try {
        p = msTable.update(person).get();
        Assert.fail();
    } catch (Exception exception) {
        // Asserts
        Assert.assertNull("Null person expected", p);

        Exception testException = null;

        if (exception instanceof ExecutionException) {
            testException = (Exception) exception.getCause();
        } else {
            testException = exception;
        }

        Assert.assertEquals("The entity has an invalid numeric value on id property.",
                testException.getMessage());
    }
}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

@Test
public void testRSAAgentConfigs() throws Exception, IDMException {
    CasIdmClient idmClient = getIdmClient();
    String tenantName = "TestTenant1";
    Tenant tenantToCreate = new Tenant(tenantName);
    try {//from   w w  w  .  j  av a2 s.c o m
        IdmClientTestUtil.ensureTenantDoesNotExist(idmClient, tenantName);
        idmClient.addTenant(tenantToCreate, DEFAULT_TENANT_ADMIN_NAME,
                DEFAULT_TENANT_ADMIN_PASSWORD.toCharArray());
    } catch (Exception ex) {
        Assert.fail("should not reach here");
    }

    try {
        Tenant tenant = idmClient.getTenant(tenantName);
        Assert.assertNotNull(tenant);
        Assert.assertEquals(tenantName, tenant.getName());
    } catch (Exception ex) {
        Assert.fail("should not reach here");
    }

    try {
        // Check default config
        AuthnPolicy authnPolicy = idmClient.getAuthnPolicy(tenantName);
        RSAAgentConfig config = authnPolicy.get_rsaAgentConfig();
        Assert.assertNull("Default rsaConfigs in a new tenant should be null.", config);

        String siteID = idmClient.getClusterId();
        String siteID2 = "siteID2";

        // Test setting config with one site
        RSAAMInstanceInfo instInfo1 = new RSAAMInstanceInfo(siteID, "TestAgent", "sdConfBytes".getBytes(),
                "sdoptsTest".getBytes());
        RSAAgentConfig configIn = new RSAAgentConfig(instInfo1);
        idmClient.setRSAConfig(tenantName, configIn);
        RSAAgentConfig configOut = idmClient.getRSAConfig(tenantName);
        AssertRSAAgentConfig(configIn, configOut);

        //test RSAAMInstanceInfo ctr
        try {
            RSAAMInstanceInfo instInfo = new RSAAMInstanceInfo(siteID, "TestAgent", null, null);
            instInfo = new RSAAMInstanceInfo(null, "", "sdConfBytes".getBytes(), null);
            instInfo = new RSAAMInstanceInfo("", "", "sdConfBytes".getBytes(), null);
            Assert.fail("should not reach here");

        } catch (IllegalArgumentException | NullPointerException e) {
        }

        // Test setting full RSA configuration and add a second site
        configIn.set_loginGuide("Test login guidence string");
        configIn.set_connectionTimeOut(10);
        configIn.set_readTimeOut(20);
        configIn.set_logFileSize(2);
        RSAAMInstanceInfo instInfo2 = new RSAAMInstanceInfo(siteID2, "TestAgent2", "sdConfBytes".getBytes(),
                null);
        configIn.add_instInfo(instInfo2);
        configIn.set_logLevel(RSAAgentConfig.RSALogLevelType.valueOf("DEBUG"));
        configIn.set_maxLogFileCount(20);
        configIn.set_rsaEncAlgList(new HashSet<String>(Arrays.asList("alg1", "alg2")));
        HashMap<String, String> idsUserIDAttributeMap = new HashMap<String, String>();
        idsUserIDAttributeMap.put("adTestIDS", "upn");
        idsUserIDAttributeMap.put("localIDS", "email");
        configIn.set_idsUserIDAttributeMaps(idsUserIDAttributeMap);

        idmClient.setRSAConfig(tenantName, configIn);
        configOut = idmClient.getRSAConfig(tenantName);
        AssertRSAAgentConfig(configIn, configOut);

        //Remove second site from RSAAgentConfig

        HashMap<String, RSAAMInstanceInfo> instMap = configIn.get_instMap();
        instMap.remove(siteID2);
        configIn.set_instMap(instMap);

        idmClient.deleteRSAInstanceInfo(tenantName, siteID2);
        configOut = idmClient.getRSAConfig(tenantName);
        AssertRSAAgentConfig(configIn, configOut);

        //Udate siteInfo attributes
        instMap = configIn.get_instMap();
        instInfo1.set_agentName("TestAgentChanged");
        instInfo1.set_sdoptsRec("sdoptsTestModified".getBytes());
        instMap.put(siteID, instInfo1);
        configIn.set_instMap(instMap);

        idmClient.setRSAConfig(tenantName, configIn);
        configOut = idmClient.getRSAConfig(tenantName);
        AssertRSAAgentConfig(configIn, configOut);

        // Test updates RSAAgentConfig attributes
        configIn.set_loginGuide("Modified login guidence string");
        configIn.set_connectionTimeOut(40);
        configIn.set_readTimeOut(50);
        configIn.set_logFileSize(70);
        configIn.set_logLevel(RSAAgentConfig.RSALogLevelType.valueOf("WARN"));
        configIn.set_maxLogFileCount(7);
        configIn.set_rsaEncAlgList(new HashSet<String>(Arrays.asList("ALG1", "ALG2")));
        idsUserIDAttributeMap = new HashMap<String, String>();
        idsUserIDAttributeMap.put("adTestIDS", "email");
        idsUserIDAttributeMap.put("localIDS", "upn");
        configIn.set_idsUserIDAttributeMaps(idsUserIDAttributeMap);

        idmClient.setRSAConfig(tenantName, configIn);
        configOut = idmClient.getRSAConfig(tenantName);
        AssertRSAAgentConfig(configIn, configOut);

    } catch (Exception e) {
        Assert.fail("should not reach here");
    } finally {

        // Cleanup
        IdmClientTestUtil.ensureTenantDoesNotExist(idmClient, tenantName);
    }
}