junit test case with null object - testing

I want to write Person class with 3 parameter constructor and if user give null string for name and surname for a person, I want to return null for that object because I want to use junit assertNull function to show that object is not created with null string.
public Person(String names,String surnames,int ages)
{
if(!names.equals(null) && !surnames.equals(null))
{
name = names;
surname = surnames;
}
else
{
return;
}
if(ages > 0)
age = ages;
else
return;
}
and test is like that
#Test
public void createPerson()
{
String ad = null;
String soyad = null;
int age = 10;
Person p = new Person(ad, soyad, age);
assertNull("Object is not created!", p );
}
how can do it I get null pointer exception?

You get a NullPointerException because you are calling the equals method on a null object. If you want to check whether a String is not null, you need to use someString != null.
What you need to do is:
if (names != null && surnames != null)
But that does not solve your problem that it is not possible to return null from a constructor. The only thing you could do ist to throw a NullPointerException—and that is exactly what your code does. There must be some other way to solve the problem you have.

Related

Whole Structure is being replaced with the last pointer Value

In my program I have used an array of pointers as a structure variable to get first name and second name from the user.
The following is my function call statement:
ret_val = update_person(&ptr_person[person_index],f_name,s_name);
where ptr_person[SIZE] is a pointer variable and f_name and s_name are character array variables.
The following is my function definition where name_ret is int:
name_ret update_person(person_name_et **person,char *first_arg,char *second_arg)
{
int val = SUCCESS, val1 = SUCCESS,val2= SUCCESS;
int f_len = sizeof(first_arg);
int s_len = sizeof(second_arg);
val2 = remove_newline(first_arg);
val1 = remove_newline(second_arg);
val = allocate_person(person, f_len, s_len);
if((val && val1) == SUCCESS)
{
(*person)->first_name = first_arg;
(*person)->second_name = second_arg;
return SUCCESS;
}
else
{
return FAILURE;
}
}
The problem in the code is it works fine at the instance but when the function is called next iteration the ptr_Person[0] is replaced with ptr_person[1] and if we have 5 instances then all the 5 variables are replaced by the last values.

My TableViewer is not sorting properly after I added a DecoratingStyledCellLabelProvider

I have a JFace TableViewer with a ViewerComparator. The direction and column of the sort is set on the selection listener of the table. This works just fine.
However, I recently changed my LabelProvider from a DelegatingStyledCellLabelProvider to a DecoratingStyledCellLabelProvider. After I made that change, the table seems to be sorting - the column gets highlighted and the directional arrow is added to the column header. The first column gets sorted the way I was expecting based on the values of the sorting column, but the rest of the rows aren't moving with it.
This is how the table looks before I try to sort. Notice the value of the first column in relation to the other values.
And after I sort. See how the 2nd column's values are in the same order they were before even though the first column is alphabetical?
My code for adding the DecoratingStyledCellLabelProvider is as follows:
column.setLabelProvider(
new DecoratingStyledCellLabelProvider(
new MyStyledCellLabelProvider(),
MyPlugin.getDefault().getWorkbench().getDecoratorManager(),
null ) );
Edited to add the compare code
#Override
public int compare( final Viewer viewer, final Object e1, final Object e2 ) {
if( !( e1 instanceof TreeElement<?> && e2 instanceof TreeElement<?> ) ) {
return super.compare(viewer, e1, e2);
}
if(this.sortDirection == SortDirection.NONE) {
return ((TreeElement<?>) e1).getSortIndex() - ((TreeElement<?>) e2).getSortIndex();
}
final IBaseLabelProvider labelProvider = ((ColumnViewer) viewer).getLabelProvider(this.columnNumber);
if( !(labelProvider instanceof DelegatingStyledCellLabelProvider) ) {
return super.compare(viewer, e1, e2);
}
final IStyledLabelProvider columnLabelProvider = ((DelegatingStyledCellLabelProvider) labelProvider).getStyledStringProvider();
final TreeElement<?> treeElement1 = (TreeElement<?>) e1;
final String text1 = columnLabelProvider.getStyledText(treeElement1).getString();
final TreeElement<?> treeElement2 = (TreeElement<?>) e2;
final String text2 = columnLabelProvider.getStyledText(treeElement2).getString();
// either one could be null
int result;
if(text1 == null) {
result = text2 == null ?
0 : // both null, so they're the same
1; // only text1 is null, so text2 is greater
} else {
result = text2 == null ?
-1 : // only text2 is null, so text1 is greater
text1.compareToIgnoreCase(text2); // both not null - do a real text compare
}
// If descending order, flip the direction
return this.sortDirection == SortDirection.DESCENDING ? -result : result;
}
EDIT 2: Adding label provider code.
My label provider extends ColumnLabelProvider and implements IStyledLabelProvider
#Override
public StyledString getStyledText(final Object element) {
if( !(element instanceof TreeElement<?>) ) {
return null;
}
final String elemText = getText(element);
final StyledString styledString = new StyledString(elemText == null ? "" : elemText);
if( !(element instanceof MyElement<?,?>) ) {
return styledString;
}
// apply styles as needed
return styledString;
}
EDIT 3: Resolution
I wasn't able to fix the issue. However, it became moot as I was able to work out a change in the design so I didn't need the DecoratingStyledCellLableProvider anyway. Thanks for all your help!

Null pointer exception with a method call

Ok this is the code for one section of my switch statement:
case 1: {
System.out.print("Member ID: ");
int key = in.nextInt();
while(members.findItemByKey(key) == -1){
System.out.print("That is an invalid member ID!\nEnter a new one: ");
key = in.nextInt();
}
System.out.print("ISBN: ");
int book = in.nextInt();
while(books.findItemByKey(book) == -1){
System.out.println("That book is not in the system.\nPlease make a new choice: ");
book = in.nextInt();
}
while(stock.findItemByKey(book) != -1){
try {
m = members.get(members.findItemByKey(key));
t = books.get(books.findItemByKey(book));
} catch (Exception e) {
e.printStackTrace();
}
if(m.checkOut(t) == true){
stock.removeItem(t);
}
}
}
Here is the method that is calling:
public int findItemByKey(int key){
for(E e: list)
{
if(e.getKey() == key){
return findItem(e);
}
}
return -1;
}
public int findItem(E item){
if (item == null){
for (int i = 0; i < numElements; i++)
if(list[i]==null)
return i;
}else {
for( int i = 0; i < numElements; i++)
if (item.equals(list[i]))
return i;
}
return -1;
}
Ok, I know there's a lot to look at here, but here's what's happening. When I enter an invalid member ID, it functions properly and keeps asking the user for a new member ID until a valid one is entered. Now when I enter a book, regardless of whether I enter a valid or invalid book, I am getting a null pointer exception thrown by this line:
if(e.getKey() == key)
books, members, and stock are all arraylists defined the same way in my code. I don't understand why I'm having this exception thrown with books and not with the members. The classes for book and member are defined the same way, both have the same getKey method within them.
Maybe there's just too much going on in this question for anyone to be able to really see what's going on. Basically I just can't understand why I get a null pointer exception with the one and not with the other.
Edit: Decided I should post the getKey() method for each class.
public int getKey()
{
return ISBN;
}
Is the one for books
public int getKey()
{
return memberId;
}
Is the one for members.
ISBN is the identifier for books and memberId is the identifier for my members. Everything looks like it's calling the same things, but it errors for books and not for members. Just don't get it.
Either this e is null or the value returned from the statement e.getKey() is null.
You have to make sure that the list doesn't contain a null element and then their keys should also be not-null.
If you want to ignore these values being null, you can do like:
if(e!=null && e.getKey()!=null && e.getKey() == key){
//statements here.
}

h:selectOneMenu not populating a 'selected' item

I'm having trouble with an h:selectOneMenu not having a selected item when there is already something set on the backing bean. I am using seam and have specified a customer converter. When working on my 'creation' page, everything works fine, something from the menu can be selected, and when the page is submitted, the correct value is assigned and persisted to the database as well.
However when I work on my 'edit' page the menu's default selection is not the current selection. I have gone through and confirmed that something is definitely set etc.
My selectOneMenu looks like this:
<h:selectOneMenu id="selVariable"
value="#{customer.variableLookup}"
converter="#{variableLookupConverter}">
<s:selectItems var="source"
value="#{customerReferenceHelper.variableLookups()}"
label="#{source.name}" />
</h:selectOneMenu>
And the converter is below. It very simple and just turns the id from string to int and back etc:
#Name( "variableLookupConverter" )
public class VariableLookupConverter implements Serializable, Converter {
#In
private CustomerReferenceHelper customerReferenceHelper;
#Override
public Object getAsObject( FacesContext arg0, UIComponent arg1, String arg2 ) {
VariableLookup variable= null;
try {
if ( "org.jboss.seam.ui.NoSelectionConverter.noSelectionValue".equals( arg2 ) ) {
return null;
}
CustomerReferenceHelper customerReferenceHelper = ( CustomerReferenceHelper ) Contexts.getApplicationContext().get(
"customerReferenceHelper" );
Integer id = Integer.parseInt( arg2 );
source = customerReferenceHelper.getVariable( id );
} catch ( NumberFormatException e ) {
log.error( e, e );
}
return variable;
}
#Override
public String getAsString( FacesContext arg0, UIComponent arg1, Object arg2 ) {
String result = null;
VariableLookup variable= ( VariableLookup ) arg2;
Integer id = variable.getId();
result = String.valueOf( id );
return result;
}
}
I've seen a few things about it possibly being the equals() method on the class, (that doesn't add up with everything else working, but I overrode it anyway as below, where the hashcode is just the id (id is a unique identifier for each item).
Equals method:
#Override
public boolean equals( Object other ) {
if ( other == null ) {
return false;
}
if ( this == other ) {
return true;
}
if ( !( other instanceof VariableLookup ) ) {
return false;
}
VariableLookup otherVariable = ( VariableLookup ) other;
if ( this.hashCode() == otherVariable.hashCode() ) {
return true;
}
return false;
}
I'm at my wits end with this, I can't find what I could have missed?! Any help would be much appreciated.
UPDATE: As I understand it, when the list is built it checks the binded value against each item to see if they match to set the selected item. Putting some debug statements in the equals method shows that all comparisons during the building of the list fail due to a comparison to a null object, but checking the seam debug page, it shows that the value is definitely set.
Try this;
<h:selectOneMenu id="selVariable"
value="#{customer.variableLookup}">
<s:selectItems var="source"
value="#{customerReferenceHelper.variableLookups()}"
label="#{source.name}" itemValue="#{source}/>
<s:convertEntity />
</h:selectOneMenu>
I'm using this notation for almost all of my entities.
EDIT
Omnifaces has a SelectItemsConverter it may solve your problem.

Searching for data in SQLite DB table

I have a text view in which user enters a string. I need to search for that string in a table and return a boolean value if a string matches.
I am not into SQL, so can anyone please help me figure out how to do it.
Assuming that you know the basics & the object db of type SQLiteDatabase exists in your DataAccessLayer, below is the function which returns true false based on whether the location exists or not?
public boolean IsRecordExists(long empid) throws SQLException
{
String where = "empid =" + empid;
Cursor mCursor = db.query(true, "employeeinfo", new String[] {"empid"}, where, null,null, null, null, null);
if (mCursor != null)
{
if(mCursor.moveToFirst())
return true;
else
return false;
}
return false;
}