JUnit's LinkedList method test fails, why?


UserFuser

I have this method which will search a LinkedList (named ListNode) and check for chars, and check if they contain uppercase chars, then store it in a new linked list, and return it. I wrote code for this and tested it with JUnit and it failed JUNit (one of those blue boxes). Does anyone know what's wrong?

Here is my LinkedList method:

public static ListNode copyUpperCase(ListNode head) {
    ListNode newListNode = mkEmpty();
    if(head == null){
        throw new ListsException("");
    }else{      
        while(head.next != null){
            if(Character.isUpperCase(head.element)){
                newListNode.element = head.element;         
            }
            head = head.next;
        }
    }
    return newListNode;
}

Here is the ListNode:

public class ListNode {
    public char element;
    public ListNode next;
}

Here is the test method:

@Test
public void testCopyUpperCase()
{
    // Inject upper case letters randomly in the test strings.
    // Assert equal results when extracting the upper case chars from
    // the corresponding list, as wheen extracting them from the 
    // injected string itself.
    for ( String s : cases ) {
        String uppersAndLowers = randInjectUpper(s);
        // Extract the upper case characters
        StringBuilder uppers = new StringBuilder();
        for ( int i = 0; i < uppersAndLowers.length(); i++ ) {
            final char c = uppersAndLowers.charAt(i);
            if ( Character.isUpperCase(c) )
                uppers.append(c);
        }
        ListNode temp = Lists.toList(uppersAndLowers);
        ListNode lhs = Lists.copyUpperCase(temp);
        assertFalse(hasSharedNodes(temp,lhs));
        ListNode rhs = Lists.toList(uppers.toString());
        assertTrue(Lists.equals(lhs,rhs));
    }
}

The failing line in the test method is the last line, which is:

assertTrue(Lists.equals(lhs,rhs));

If it fails on that line, what does that mean?

ps. This is also the equals method:

// Two lists are equal if both are empty, or if they have equal lengths
// and contain pairwise equal elements at the same positions.
public static boolean equals(ListNode l1,ListNode l2) {
    if ( isEmpty(l1) && isEmpty(l2) )
        return true;
    else if ( isEmpty(l1) || isEmpty(l2) )
        return false;
    else { // both lists are non-empty
        ListNode p1 = l1.next, p2 = l2.next;
        while ( p1 != null && p2 != null ) {
            char c1 = p1.element, c2 = p2.element;
            if ( p1.element != p2.element )
                return false;
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1 == null && p2 == null;
    }
}

EDIT: Here is the new method:

public static ListNode copyUpperCase(ListNode head) {

    ListNode newListNode = mkEmpty();
    if(head == null){
        throw new ListsException("Lists: null passed to copyUpperCase");
    }else{
        String cpy = toString(head);
        char[] chry = cpy.toCharArray();
        for(int i = 0; i < chry.length ; i++ )
                if(Character.isUpperCase(chry[i])){
                    newListNode.element = chry[i];      
                }
                newListNode = newListNode.next;
        }           
    return newListNode;
}
Soul Master

Your equals method seems to be ok. It correctly checks if both lists are empty, then correctly checks if one list is empty and the other is empty. After that, you iterate over both lists at the same time, checking each character, and at the end, expect both pointers to be null. Everything is fine.

So the problem must be in the toListmethod or in the copyUppercasemethod. Indeed, your copyUppercaseapproach is buggy. Ask yourself, what happens to a list with only one element? Then ask yourself, what will happen to the last element of the provided list? Can you see the sights?

while loop condition is false: it must simply be

while (head != null) { ... }

Related


JUnit's LinkedList method test fails, why?

UserFuser I have this method which will search a LinkedList (named ListNode) and check for chars, and check if they contain uppercase chars, then store it in a new linked list, and return it. I wrote code for this and tested it with JUnit and it failed JUNit (

Run a method if the test fails on Junit

Keva 161 I've added a method to my Selenium framework that takes a screenshot at the end of a test, but it doesn't run all the way to the end because some tests fail. I want to implement a rule to run this screenshot method if the test fails. It's just like: @

Can anyone explain why the JUnit test fails?

A0sXc950 I am writing a piece of code that involves matrices. The code I compile for ArrayMatrix has no errors, but when I try to run a JUnit test on the code, I get an error. At this point, I'm not sure if I'm doing it right. public class ArrayMatrix extends

Travis fails in Spring's JUnit test

px06 I've written some tests that run flawlessly on my machine and on the machine I'm using to deploy/test the server on. Travis seems to have a problem with that. Before the test starts, I'm loading some entities @Beforelike this: @Transactional public void l

Why does a JUnit test method have to be invalid?

Artem Malchenko: I've read a lot of places that this test method should/must void, but none of them say the reason for this. I found that MethodValidator has no comments/javadoc for the following checks. if (each.getReturnType() != Void.TYPE) { err

Why does a JUnit test method have to be invalid?

Artem Malchenko: I've read a lot of places that this test method should/must void, but none of them say the reason for this. I found that MethodValidator has no comments/javadoc for the following checks. if (each.getReturnType() != Void.TYPE) { err

Why does a JUnit test method have to be invalid?

Artem Malchenko: I've read a lot of places that this test method should/must void, but none of them say the reason for this. I found that MethodValidator has no comments/javadoc for the following checks. if (each.getReturnType() != Void.TYPE) { err

Why does a JUnit test method have to be invalid?

Artem Malchenko: I've read a lot of places that this test method should/must void, but none of them say the reason for this. I found that MethodValidator has no comments/javadoc for the following checks. if (each.getReturnType() != Void.TYPE) { err

Junit Test: Repository's findById method

firefighter I am new to Junit testing and I have a question about this. Here you can see the findById method in my service class : @Service public class DefaultQuarterService implements QuarterService { private final QuarterRepository quarterRepository;

JUnit test fails when annotating method arg @Nonnull

Freddy Boucher: Can someone explain why my JUnit tests are failing: notNullMethodTest() using @NotNull -> success nonnullMethodTest() with @Nonnull - > fails Unexpected exception, expected <java.lang.NullPointerException>, but got <java.lang.IllegalArgumentExc

JUnit test fails with NPE when testing validator method

Sudir I am going through the following tutorial: http://docs.spring.io/docs/Spring-MVC-step-by-step/part4.html I am trying to test the validate method in the class below: public class PriceIncreaseValidator implements Validator { public void validate(Objec

JUnit test fails with NPE when testing validator method

Sudir I am working through the following tutorial: http://docs.spring.io/docs/Spring-MVC-step-by-step/part4.html I am trying to test the validate method in the class below: public class PriceIncreaseValidator implements Validator { public void validate(Obj

JUnit test fails when annotating method arg @Nonnull

Freddy Boucher: Can someone explain why my JUnit tests are failing: notNullMethodTest() using @NotNull -> success nonnullMethodTest() with @Nonnull - > fails Unexpected exception, expected <java.lang.NullPointerException>, but got <java.lang.IllegalArgumentExc

JUnit test fails with NPE when testing validator method

Sudir I am working through the following tutorial: http://docs.spring.io/docs/Spring-MVC-step-by-step/part4.html I am trying to test the validate method in the class below: public class PriceIncreaseValidator implements Validator { public void validate(Obj

junit test fails with exception

Sebastian Dietrich I am using junit to test my Metrics class. When the test runs, I don't get any exceptions, but the test doesn't succeed. I've tried to find all the different questions but haven't found any. Here is its code. public class MetricsTest { pri

jUnit test on JAVA fails

k2wln I'm new here and sorry for the stupid question. I have some problems with my JUnit test: for some reason it shows me an error in index.html. I attach the link to my repository through tests and screens. Thanks! mistake: org.opentest4j.AssertionFailedErro

junit TestWatcher fails and completes method's trigger time

Erki M. I'm writing some functional tests using Webdriver and executing them using JUnit. I am trying to utilize the TestWatcher class so that I can perform a specific action every time an event occurs. I have overridden the finish and fail methods, but it see

junit TestWatcher fails and completes method's trigger time

Erki M. I'm writing some functional tests using Webdriver and executing them using JUnit. I am trying to utilize the TestWatcher class so that I can perform a specific action every time an event occurs. I have overridden the finish and fail methods, but it see

JUnit test for @override method

Brandon Bischoff: I have a program with a class below it: public class Plane implements Flyable { private final int numberOfEngines; private final String model; public Plane(int engines, String m) { numberOfEngines = engines;

Test the main method with junit

user2719152: I have written a class which takes data from console and input parameters in main method. The main method calls different methods for different console inputs, and calls different functions for different parameters. So I want to test this main met

JUNIT test void method

between I have a Java class full of void methods and I want to do some unit tests for maximum code coverage. For example I have this method: protected static void checkifValidElements(int arg1, int arg2) { method1(arg1); method2(arg1); method3(arg

Junit test method

Eugene: What are the most common testing methods I should use first in order to become familiar with unit testing? There are a lot of them, but I guess something like normal. I mean Junit methods like AssertTrue() etc. Andy Thomas: There are only a few pattern

Junit test boolean method

Splitter I have a problem writing a test case in the following method:EvenNum(double) public class OddEven { /** * @param args */ public boolean evenNum(double num) { if(num%2 == 0) { System.out.print(true); return true; } e

JUnit test transaction method

Tudani Hetimura I am new to JUnit and trying to test a spring web service using JPA DAO. I need to test a service method similar to the following. Service methods are annotated @Transactional(propagation=Propagation.REQUIRED)and ServiceObjectRepository.update(

Test the main method with junit

user2719152: I have written a class which takes data from console and input parameters in main method. The main method calls different methods for different console inputs, and calls different functions for different parameters. So I want to test this main met

JUNIT test void method

between I have a Java class full of void methods and I want to do some unit tests for maximum code coverage. For example I have this method: protected static void checkifValidElements(int arg1, int arg2) { method1(arg1); method2(arg1); method3(arg