Java Code Examples for junit.framework.Assert#fail()

The following examples show how to use junit.framework.Assert#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: JDBC.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Assert that a ResultSet representing generated keys is non-null
 * and of the correct type. This method leaves the ResultSet
 * open and does not fetch any date from it.
 * 
 * @param description For assert messages
 * @param keys ResultSet returned from getGeneratedKeys().
 * @throws SQLException
 */
public static void assertGeneratedKeyResultSet(
        String description, java.sql.ResultSet keys) throws SQLException
{
    
    Assert.assertNotNull(description, keys);
    
    // Requirements from section 13.6 JDBC 4 specification
    Assert.assertEquals(
            description + 
            " - Required CONCUR_READ_ONLY for generated key result sets",
            java.sql.ResultSet.CONCUR_READ_ONLY, keys.getConcurrency());
    
    int type = keys.getType();
    if ( (type != java.sql.ResultSet.TYPE_FORWARD_ONLY) &&
         (type != java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE))
    {
        Assert.fail(description +
                " - Invalid type for generated key result set" + type);
    }
    
    

}
 
Example 2
Source File: MockClusterInvokerTest.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMockInvokerFromOverride_Invoke_force_throwCustemException() throws Throwable{
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("getBoolean2.mock","force:throw com.alibaba.dubbo.rpc.cluster.support.wrapper.MyMockException")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getBoolean2");
	try {
		cluster.invoke(invocation).recreate();
		Assert.fail();
	} catch (MyMockException e) {
		
	}
}
 
Example 3
Source File: OpExecutorImplJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testRetryFailedServers() throws Exception {
  OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 10, 10, false, logger.convertToLogWriterI18n(), cancelCriterion, null);
  
  manager.numServers = 5;
  try {
    exec.execute(new Op() {
      public Object attempt(Connection cnx) throws Exception {
        throw new IOException("Something didn't work");
      }
      @Override
      public boolean useThreadLocalConnection() {
        return true;
      }
    });
    Assert.fail("Should have got an exception");
  } catch(ServerConnectivityException expected) {
    //do nothing
  }
  Assert.assertEquals(1, borrows);
  Assert.assertEquals(10, exchanges);
  Assert.assertEquals(1, returns);
  Assert.assertEquals(11, invalidateConnections);
  Assert.assertEquals(11, serverCrashes);
}
 
Example 4
Source File: EOSWalletTest.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
@Test
public void importEOSWalletFailedWhenDerivedPubKeyNotSame() {
  try {
    List<EOSKeystore.PermissionObject> permissionObjects = new ArrayList<>();
    EOSKeystore.PermissionObject permObj = new EOSKeystore.PermissionObject();
    // this pubkey is wrong, the last letter should be w not W
    permObj.setPublicKey("EOS7tpXQ1thFJ69ZXDqqEan7GMmuWdcptKmwgbs7n1cnx3hWPw3jW");
    permObj.setPermission("owner");
    permissionObjects.add(permObj);

    permObj = new EOSKeystore.PermissionObject();
    permObj.setPublicKey("EOS5SxZMjhKiXsmjxac8HBx56wWdZV1sCLZESh3ys1rzbMn4FUumU");
    permObj.setPermission("active");
    permissionObjects.add(permObj);

    WalletManager.importWalletFromMnemonic(eosMetadata(), ACCOUNT_NAME, SampleKey.MNEMONIC, BIP44Util.EOS_LEDGER, permissionObjects, SampleKey.PASSWORD, true);
    Assert.fail("Should throw exception");
  } catch (TokenException ex) {
    Assert.assertEquals(Messages.EOS_PRIVATE_PUBLIC_NOT_MATCH, ex.getMessage());
  }

}
 
Example 5
Source File: TheSettingsShould.java    From android-sdk with MIT License 6 votes vote down vote up
public void test_advertising_id_gets_persisted() throws Exception {
        //prepare the shared preferences
        Assert.fail();
//        Assertions.assertThat(untouched.getAdvertisingIdentifier()).isNull();
//        Assertions.assertThat(tested.getAdvertisingIdentifier()).isEqualTo(untouched.getAdvertisingIdentifier());
//        Assertions.assertThat(testedSharedPreferences.getString(Constants.SharedPreferencesKeys.Network.ADVERTISING_IDENTIFIER, "")).isEmpty();
//
//        tested.setAdvertisingIdentifier("TEST_ID");
//        Assertions.assertThat(testedSharedPreferences.getString(Constants.SharedPreferencesKeys.Network.ADVERTISING_IDENTIFIER, "")).isEqualTo(
//                "TEST_ID");
//
//        //load the last values from the shared preferences, as it happens after a restart
//        tested.restoreValuesFromPreferences();
//        Assertions.assertThat(tested.getAdvertisingIdentifier()).isEqualTo("TEST_ID");
//
//        //simulating a settings request without content
//        tested.onSettingsFound(new JSONObject());
//        Assertions.assertThat(tested.getAdvertisingIdentifier()).isEqualTo("TEST_ID");
    }
 
Example 6
Source File: Test_VkPreise.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testVKMultiplikator()  throws SQLException 
{
	Eigenleistung leistung = new Eigenleistung("TD999", "Leistung.xy999", "99", "10");
	TimeTool now = new TimeTool(System.currentTimeMillis());
	leistung.setVKMultiplikator(now, null, 98.12345, "typ");
	Assert.assertEquals(98.12345, leistung.getVKMultiplikator(now, "typ"));
	
	ResultSet res = link.getStatement().query("SELECT ID FROM VK_PREISE WHERE TYP='typ'");
	if (res.next())
	{
		// checks if id is generated successfully after insert
		Assert.assertNotNull(res.getString("ID"));
	}
	else
	{
		Assert.fail("no result for vk_preise");
	}
	
}
 
Example 7
Source File: TestUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of x.
 * 
 * @param msg  message to return with failure
 * @param values double array to search
 * @param x value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, double[] values,
        double x, double epsilon) {
    int i = 0;
    boolean found = false;
    while (!found && i < values.length) {
        try {
            assertEquals(values[i], x, epsilon);
            found = true; 
        } catch (AssertionFailedError er) {
            // no match
        }
        i++;
    }
    if (!found) {
        Assert.fail(msg + " Unable to find" + x);
    }
}
 
Example 8
Source File: TestTFileByteArrays.java    From RDFS with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureReadValueManyTimes() throws IOException {
  if (skip)
    return;
  writeRecords(5);

  Reader reader = new Reader(fs.open(path), fs.getFileStatus(path).getLen(), conf);
  Scanner scanner = reader.createScanner();

  byte[] vbuf = new byte[BUF_SIZE];
  int vlen = scanner.entry().getValueLength();
  scanner.entry().getValue(vbuf);
  Assert.assertEquals(new String(vbuf, 0, vlen), VALUE + 0);
  try {
    scanner.entry().getValue(vbuf);
    Assert.fail("Cannot get the value mlutiple times.");
  } catch (Exception e) {
    // noop, expecting exceptions
  }

  scanner.close();
  reader.close();
}
 
Example 9
Source File: TestTFileByteArrays.java    From RDFS with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureOpenEmptyFile() throws IOException {
  if (skip)
    return;
  closeOutput();
  // create an absolutely empty file
  path = new Path(fs.getWorkingDirectory(), outputFile);
  out = fs.create(path);
  out.close();
  try {
    new Reader(fs.open(path), fs.getFileStatus(path).getLen(), conf);
    Assert.fail("Error on handling empty files.");
  } catch (EOFException e) {
    // noop, expecting exceptions
  }
}
 
Example 10
Source File: MultiDBPreparedStatementLifeCycleTest.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiRouterResult16() throws Exception {
    DataSource ds = (DataSource) context.getBean("zebraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        PreparedStatement stmt = conn
                .prepareStatement("select distinct score from test order by score asc limit ?,?");
        stmt.setInt(1, 7);
        stmt.setInt(2, 10);
        stmt.execute();
        ResultSet rs = stmt.getResultSet();
        int count = 0;
        while (rs.next()) {
            count++;
        }
        Assert.assertEquals(2, count);
    } catch (Exception e) {
        Assert.fail();
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
}
 
Example 11
Source File: PollingCheck.java    From android-dev-challenge with Apache License 2.0 5 votes vote down vote up
public static void check(CharSequence message, long timeout, Callable<Boolean> condition)
        throws Exception {
    while (timeout > 0) {
        if (condition.call()) {
            return;
        }

        Thread.sleep(TIME_SLICE);
        timeout -= TIME_SLICE;
    }

    Assert.fail(message.toString());
}
 
Example 12
Source File: TestConfigOptionParser.java    From Eagle with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidCommandArgument2()  {
    String[] arguments = new String[]{
            "-D","=value"
    };

    try {
        new ConfigOptionParser().parseConfig(arguments);
        Assert.fail("Should throw ParseException");
    } catch (ParseException e) {
        LOG.info("Expected exception: " + e.getMessage());
    }
}
 
Example 13
Source File: TLCVariableValueTest.java    From tlaplus with MIT License 5 votes vote down vote up
public void testGetNextChar2()
{
    String test = "1234567";
    try
    {
        TLCVariableValue.getNextChar(new InputPair(test, 7));
        Assert.fail();
    } catch (VariableValueParseException e)
    {
        Assert.assertTrue(true);
    }
}
 
Example 14
Source File: TestEagleQueryParser.java    From Eagle with Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexExpressionWithAndCondition(){
	String query = "(EXP{@a + @b} > 3) AND (@b >10)";
	EagleQueryParser parser = new EagleQueryParser(query);
	ORExpression or = null;
	try{
		or = parser.parse();
	}catch(EagleQueryParseException ex){
		Assert.fail(ex.getMessage());
	}
	Assert.assertTrue(or.getANDExprList().size()==1);
	ANDExpression and = or.getANDExprList().get(0);
	Assert.assertEquals(2, and.getAtomicExprList().size());
	Assert.assertEquals("a + b>3", and.getAtomicExprList().get(0).toString());
	Assert.assertEquals("@b>10", and.getAtomicExprList().get(1).toString());
	
	AtomicExpression leftExpression = and.getAtomicExprList().get(0);
	Assert.assertEquals("a + b", leftExpression.getKey());
	Assert.assertEquals(TokenType.EXP, leftExpression.getKeyType());
	Assert.assertEquals(">", leftExpression.getOp().toString());
	Assert.assertEquals("3", leftExpression.getValue());
	Assert.assertEquals(TokenType.NUMBER, leftExpression.getValueType());
	AtomicExpression rightExpression = and.getAtomicExprList().get(1);
	Assert.assertEquals("@b", rightExpression.getKey());
	Assert.assertEquals(TokenType.ID, rightExpression.getKeyType());
	Assert.assertEquals(">", rightExpression.getOp().toString());
	Assert.assertEquals("10",rightExpression.getValue());
	Assert.assertEquals(TokenType.NUMBER, rightExpression.getValueType());
}
 
Example 15
Source File: SoapBookmarkServiceTest.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testBookmarkDocument() throws Exception {
	bookmarkService.bookmarkDocument("", 1L);
	bookmarkService.bookmarkDocument("", 2L);

	WSBookmark[] bookmarks = bookmarkService.getBookmarks("");
	Assert.assertEquals(2, bookmarks.length);

	try {
		bookmarkService.bookmarkDocument("", 3L);
		Assert.fail("the document doesn't exist, why exception was not raised.");
	} catch (Throwable t) {
		// We expect to be here
	}
}
 
Example 16
Source File: ScaleVMCmdTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSuccess() {

    final UserVmService userVmService = Mockito.mock(UserVmService.class);
    final UserVm userVm = Mockito.mock(UserVm.class);

    try {
        Mockito.when(userVmService.upgradeVirtualMachine(scaleVMCmd)).thenReturn(userVm);
    } catch (final Exception e) {
        Assert.fail("Received exception when success expected " + e.getMessage());
    }

    final ResponseGenerator responseGenerator = Mockito.mock(ResponseGenerator.class);
    scaleVMCmd._responseGenerator = responseGenerator;

    final UserVmResponse userVmResponse = Mockito.mock(UserVmResponse.class);
    //List<UserVmResponse> list = Mockito.mock(UserVmResponse.class);
    //list.add(userVmResponse);
    //LinkedList<UserVmResponse> mockedList = Mockito.mock(LinkedList.class);
    //Mockito.when(mockedList.get(0)).thenReturn(userVmResponse);

    final List<UserVmResponse> list = new LinkedList<>();
    list.add(userVmResponse);

    Mockito.when(responseGenerator.createUserVmResponse(ResponseView.Restricted, "virtualmachine", userVm)).thenReturn(
            list);

    scaleVMCmd._userVmService = userVmService;

    scaleVMCmd.execute();
}
 
Example 17
Source File: NodeTest.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void updateFeature(){
    SparseArray <Class <? extends Feature> > temp = new SparseArray<>();
    temp.append(0x01,FakeFeature.class);
    try {
        Manager.addFeatureToNode((byte)0x00,temp);
    } catch (InvalidFeatureBitMaskException e) {
        Assert.fail("Impossible add the FakeFeature");
    }

    BluetoothDevice device = spy(Shadow.newInstanceOf(BluetoothDevice.class));
    BluetoothDeviceShadow shadowDevice = Shadow.extract(device);
    BluetoothGattService dataService = new BluetoothGattService(
            UUID.randomUUID(),
            BluetoothGattService.SERVICE_TYPE_PRIMARY);
    BluetoothGattCharacteristic dataChar = createReadNotifyChar(
            UUID.fromString("000000001-" + BLENodeDefines.FeatureCharacteristics.BASE_FEATURE_COMMON_UUID)
    );
    dataService.addCharacteristic(dataChar);
    shadowDevice.addService(dataService);
    Node n = createNode(device);
    n.connect(RuntimeEnvironment.application);

    TestUtil.execAllAsyncTask();

    BluetoothGatt gatt = shadowDevice.getGattConnection();
    Feature.FeatureListener emptyListener = mock(Feature.FeatureListener.class);
    FakeFeature f = n.getFeature(FakeFeature.class);
    Assert.assertTrue(f != null);
    f.addFeatureListener(emptyListener);
    Assert.assertTrue(n.enableNotification(f));

    TestUtil.execAllAsyncTask();
    f.execAllTask();

    verify(gatt).setCharacteristicNotification(dataChar, true);
    verify(emptyListener).onUpdate(eq(f), any(Feature.Sample.class));

    Assert.assertTrue(n.disableNotification(f));
    verify(gatt).setCharacteristicNotification(dataChar, false);
}
 
Example 18
Source File: TestDetachedListUsesCache.java    From reladomo with Apache License 2.0 4 votes vote down vote up
public static void failNotEquals(String message, Object expected, Object actual)
{
    Assert.fail(format(message, expected, actual));
}
 
Example 19
Source File: WaitActionTest.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void TestWaitForMessageWithUpdatedCheckPointInvalid2() throws Exception
{
       IMessage f1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	f1.addField("InstrumentClassId", "AAA");
       IMessage f2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	f2.addField("InstrumentClassId", "BBB");
       IMessage f3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	f3.addField("InstrumentClassId", "CCC");
       IMessage f4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	f4.addField("InstrumentClassId", "DDD");

	MetaContainer metaContainer = new MetaContainer();

       ComparatorSettings settings = new ComparatorSettings();
	settings.setMetaContainer(metaContainer);

	CollectorServiceHandler handler = new CollectorServiceHandler();
	ISession isession = new FakeSession(null);
       IMessage m1 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	m1.addField("InstrumentClassId", "AAA");
	handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m1);

	CheckPoint checkPoint = new CheckPoint(true);
       handler.registerCheckPoint(isession, ServiceHandlerRoute.FROM_APP, checkPoint);

       IMessage m2 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	m2.addField("InstrumentClassId", "BBB");
	handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m2);

       IMessage m3 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	m3.addField("InstrumentClassId", "CCC");
	handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m3);

       IMessage m4 = messageFactory.createMessage("InstrumentDirectoryDerivatives", "namespace");
	m4.addField("InstrumentClassId", "DDD");
	handler.putMessage(isession, ServiceHandlerRoute.FROM_APP, m4);

	MapMessage o = (MapMessage) WaitAction.waitForMessage(actionContext, serviceName.toString(), f3, handler, isession, checkPoint, 1000, false, true, true, settings);

	Assert.assertEquals(m3, o);
	Assert.assertEquals(3, handler.getCheckPointIndex(isession, ServiceHandlerRoute.FROM_APP, checkPoint));

	try {
		o = (MapMessage) WaitAction.waitForMessage(actionContext, serviceName.toString(), f2, handler, isession, checkPoint, 1000, false, true, true, settings);
		Assert.fail();
	} catch (EPSCommonException e)
	{
           Assert.assertTrue(e.getMessage().startsWith("Timeout. No messages matching filter from the checkpoint till the timeout is exceeded appx"));
		return;
	}

	Assert.assertTrue(false);
}
 
Example 20
Source File: MobileServiceTableTests.java    From azure-mobile-apps-android-client with Apache License 2.0 4 votes vote down vote up
public void testOperationWithErrorAndNoContentShowStatusCode() throws Throwable {

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

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

        // Add a filter to handle the request and create a new JSon
        // object with an id defined
        client = client.withFilter(new ServiceFilter() {

            @Override
            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) {

                ServiceFilterResponseMock response = new ServiceFilterResponseMock();
                response.setStatus(new StatusLine(Protocol.HTTP_2, 500, ""));

                response.setContent((String) null);
                // call onResponse with the mocked response

                final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

                resultFuture.setException(new MobileServiceException("Error while processing request", new MobileServiceException(String.format("{'code': %d}",
                        response.getStatus().code))));

                return resultFuture;

            }
        });

        // Create get the MobileService table
        MobileServiceJsonTable msTable = client.getTable(tableName);

        JsonObject json = new JsonParser().parse("{'myField': 'invalid value'}").getAsJsonObject();

        // Call the insert method
        try {
            msTable.insert(json).get();
            Assert.fail();
        } catch (Exception exception) {

            Exception testException = null;

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

            assertTrue(testException instanceof MobileServiceException);
            assertTrue(testException.getCause().getMessage().contains("500"));
        }
    }