How to test Binary Tree using Junit? - java

How do I develop JUnit test for the BinaryTree class that I've written?
Please advise or provide examples so I can have better understand how to test binary tree in Junit.
package binaryTree;
import javax.xml.soap.Node;
public class BinaryTree<T extends Comparable<T>> implements BTree<T> {
private TreeNode root;
Node current = (Node) root;
#Override
public void insert(T value) {
if (root == null) {
root = new TreeNode(value);
} else if (value.compareTo(value()) < 0) {
root.getleft().insert(value);
} else {
root.right().insert(value);
}
}
#Override
public T value() {
if (this.root != null) {
return (T) this.root.value();
} else {
return null;
}
}
#Override
public BTree<T> left() {
if (this.root != null) {
return this.root.getleft();
} else {
return null;
}
}
#Override
public BTree<T> right() {
if (this.root != null) {
return this.root.right();
} else {
return null;
}
}
}

Definitely read the docs in #tpitsch's post. But here's a simple example to get you started.
import static org.junit.Assert.*;
import org.junit.Test;
// This test class contains two test methods
public class SimpleTest {
private int add(int a, int b) {
return a + b;
}
#Test public void test1() throws Exception
{
System.out.println("#Test1");
assertEquals(add(1, 1), 2);
}
#Test public void test2() throws Exception
{
System.out.println("#Test2");
assertEquals(add(100, -30), 70);
}
}
We're testing the function add.
Each function with the #Test annotation is a JUnit test method. Each test method is run as a separate JUnit test. Function names test1() and test2() are not important.
In a test method, you can place assertions such as assertEquals() that make sure the add function is running as expected.

Related

Conditional calling using static factory method

This is my project structure. I'm trying to use a static factory function to check for an object and then perform some operations. I followed the this process.
Parent Class:
public abstract class Parent {
protected static Child1DTO ch1;
protected static Child2DTO ch2;
public Parent(Child1DTO ch1) {
this.ch1 = ch1;
}
public Parent(Child2DTO ch2) {
this.ch2 = ch2;
}
protected Parent() {
}
public static Child1DTO getCh1() {
return ch1;
}
public static Child2DTO getCh2() {
return ch2;
}
public static Class<?> childType(Object obj) {
if (obj instanceof Child1DTO) {
//do something
return Child1DTO.class;
} else if (obj instanceof Child2DTO) {
//do something
return Child2DTO.class;
}
return null;
}
}
Child1DTO Class:
public class Child1DTO extends Parent {
private String fName1;
private String lName1;
public String getfName1() {
return fName1;
}
public void setfName1(String fName1) {
this.fName1 = fName1;
}
public String getlName1() {
return lName1;
}
public void setlName1(String lName1) {
this.lName1 = lName1;
}
}
Child2DTO Class:
public class Child2DTO extends Parent{
private String fName2;
private String lName2;
public String getfName2() {
return fName2;
}
public void setfName2(String fName2) {
this.fName2 = fName2;
}
public String getlName2() {
return lName2;
}
public void setlName2(String lName2) {
this.lName2 = lName2;
}
}
Child Class:
public class Child extends Parent {
public Child(Child1DTO ch1) {
super(ch1);
}
public Child(Child2DTO ch2) {
super(ch2);
}
public static Child test(Object obj) {
if (obj instanceof Child1DTO) { //is this the correct way to check?
//do something
return new Child((Child1DTO) obj);
} else if (obj instanceof Child2DTO) {//is this the correct way to check?
//do something
return new Child((Child2DTO) obj);
}
return null;
}
public static void main(String args[]) {
if(childType(ch1).equals(ch1)){
//do something
}else if(childType(ch2).equals(ch2)){
//do something
}else{
System.out.println("Failed!");
}
}
}
EDIT:
Parent class has one Child class and two DTOs Child1DTO and Child2DTO.
Do I need to implement conditional check in Parent class or Child class?
How to achieve conditional check with constructors?

Can I check if a void method returned?

I just want to ask, if it is possible to check if a void method "cancelled" itself by calling return;?
For example in my main I call calculate(myArray);, which is defined as follows:
public static void calculate(Object[] array) {
if (array == null)
return;
// do stuff
}
Is their a way to know, if it returned or not? My thoughts were making a "global" boolean which is changed to true right before we return and then check its value in main or just change the return type to something like int and when it returned at the beginning we use return -1; and at the end of the method return 0;
Both is possible but I think neither of them is very good style. Is there an alternative?
You are right that the practices you described are considered bad in Java (and other modern languages).
The most common acceptable practices for your scenario are:
Make the method throw an exception. Do this if the "failing" code path shouldn't happen under normal circumstances.
Make the method's return type bool to indicate success or failure. Do this if the "failing" code path can happen under normal circumstances as well.
No, you cannot. From The Oracle Java tutorials - Returning a Value from a Method:
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
There is no way from method invocation to determine if the void method was completed by a fall-through block or a return; statement.
Most other methods includes a return type of boolean and returns false when something went wrong, or simply throws an IllegalArgumentException.
You can utilize publisher - listener pattern :)
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
public class Sample {
private interface Event {
}
private static class ExitEvent implements Event {
}
private static class SucceedEvent implements Event {
}
private interface EventListener {
void eventPerformed(Event e);
}
private static List<EventListener> listeners = new LinkedList<EventListener>();
private static void addActionListener(EventListener l) {
listeners.add(l);
}
private static void fireEvent(Event event) {
for (EventListener l : listeners) {
l.eventPerformed(event);
}
}
public static void calculate(Object[] array) {
if (array == null) {
fireEvent(new ExitEvent());
return;
}
fireEvent(new SucceedEvent());
}
public static void main(String[] args) {
addActionListener(new EventListener() {
public void eventPerformed(Event e) {
if (e instanceof ExitEvent) {
System.out.println("Exit");
} else if (e instanceof SucceedEvent) {
System.out.println("Success");
}
}
});
calculate(null);
calculate(new Object[] {});
}
}
Output:
Exit
Success
You can go much farther and remove those ugly ifs, by utilizing visitor pattern
import java.util.LinkedList;
import java.util.List;
public class Sample {
private interface EventVisitor {
void visit(ExitEvent event);
void visit(SucceedEvent event);
}
private interface Event {
void accept(EventVisitor visitor);
}
private static class ExitEvent implements Event {
public void accept(EventVisitor visitor) {
visitor.visit(this);
}
}
private static class SucceedEvent implements Event {
public void accept(EventVisitor visitor) {
visitor.visit(this);
}
}
private interface EventListener {
void eventPerformed(Event e);
}
private static List<EventListener> listeners = new LinkedList<EventListener>();
private static void addActionListener(EventListener l) {
listeners.add(l);
}
private static void fireEvent(Event event) {
for (EventListener l : listeners) {
l.eventPerformed(event);
}
}
public static void calculate(Object[] array) {
if (array == null) {
fireEvent(new ExitEvent());
return;
}
fireEvent(new SucceedEvent());
}
public static void main(String[] args) {
addActionListener(new EventListener() {
public void eventPerformed(Event e) {
e.accept(new EventVisitor() {
public void visit(SucceedEvent event) {
System.out.println("Success");
}
public void visit(ExitEvent event) {
System.out.println("Exit");
}
});
}
});
calculate(null);
calculate(new Object[] {});
}
}
Output:
Exit
Success

Akka Java OneForOneStrategy example not compiling

I'm trying to paste the OneForOneStrategy into a simple Hello-Akka program, like so based on this documentation: http://doc.akka.io/docs/akka/2.3.2/java/fault-tolerance.html
private static SupervisorStrategy strategy = new OneForOneStrategy(10,
Duration.create("1 minute"),
new Function<Throwable, SupervisorStrategy.Directive>() {
#Override
public SupervisorStrategy.Directive apply(Throwable t) {
if (t instanceof ArithmeticException) {
return resume();
} else if (t instanceof NullPointerException) {
return restart();
} else if (t instanceof IllegalArgumentException) {
return stop();
} else {
return escalate();
}
}
}
);
#Override
public SupervisorStrategy supervisorStrategy() {
return strategy;
}
However, the resume/restart/stop/escalate method calls don't compile out of the box.
Why not?
Just add import listed below:
import static akka.actor.SupervisorStrategy.escalate;
import static akka.actor.SupervisorStrategy.restart;
import static akka.actor.SupervisorStrategy.resume;
import static akka.actor.SupervisorStrategy.stop;
I've resolved this issue. You just need to return SupervisorStrategy.resume(), SupervisorStrategy.restart() ... etc.

Override expectations in JMockit

I want to override a previously defined expectation in JMockit. This is what I tried (see code below) -- I have a private class where I record all the common expectations and I replay it in various test methods. However, one of my method needs most of the common expectations except for few. First, I am calling the CommonNonStrictExpectations private class and then defining test specific expectations in my testMethod1 with a hope that what I defined here overrides what I have defined earlier. I dont think this way of overriding works, is there a way that works?
//MyClassTest.java
import MyClass;
public class MyClassTest {
#Mocked Someobject object;
#Test
public void testMethod1() throws Exception {
new CommonNonStrictExpectations() {};
new NonStrictExpectations() {
{
object.getInt(anyInt); returns (-1);
object.getString(anyInt); returns ("failure");
}
};
System.out.println("position: " + object.getInt(1));
System.out.println("exec status: " + object.getString(1));
MyClass m = new MyClass();
m.method(object, -1);
}
private class CommonNonStrictExpectations extends NonStrictExpectations {
public CommonNonStrictExpectations () throws Exception {
object.getInt(anyInt); returns (anyInt);
object.getString(anyInt); returns ("success");
}
}
}
//MyClass.java
import Someobject;
public class MyClass {
public void method (Someobject someobject, int i) {
String status = someobject.getString(i);
if (status.equalsIgnoreCase("success")) {
print(someobject, "success");
} else if (status.equalsIgnoreCase("failure")) {
print(someobject, "failure");
} else
print(someobject, "");
}
private String print(Someobject someobject, String status) {
return someobject.printMessage (status);
}
}
// Someobject.java
public class Someobject {
public String getString(int i) {
if (i < 0)
return "failure";
else if (i > 0)
return "success";
else
return "";
}
public int getInt(int k) {
return k;
}
public String printMessage (String status) {
return "status is: " + status;
}
}

Java / JUnit - comparing two polynomial objects

I have a Java class called Term holding polynomials like below
public Term(int c, int e) throws NegativeExponent {
if (e < 0) throw new NegativeExponent();
coef = c;
expo = (coef == 0) ? 1 : e;
}
I also have an equals method in the same class like below
#Override
public boolean equals(Object obj) {
}
I am stuck with how to code how to compare these 2 Term objects
Within my JUnit test file I am using the test below to try and test the equals method
import static org.junit.Assert.*;
import org.junit.Test;
public class ConEqTest
{
private int min = Integer.MIN_VALUE;
private int max = Integer.MAX_VALUE;
#Test
public void eq01() throws TError { assertTrue(new Term(-10,0).equals(new Term(-10,0))); }
#Test
public void eq02() throws TError { assertTrue(new Term(0,0).equals(new Term(0,2))); }
What's wrong with
#Override
public boolean equals(Object obj) {
if (! (obj instanceof Term))
return false;
Term t = (Term)obj;
return coef == t.coef && expo == t.expo;
}
import static org.junit.Assert.*;
import org.junit.*;
#SuppressWarnings("serial") class NegativeExponentException extends Exception {}
class Term {
#Override public int hashCode() {
final int prime=31;
int result=1;
result=prime*result+coefficient;
result=prime*result+exponent;
return result;
}
#Override public boolean equals(Object obj) {
if(this==obj)
return true;
if(obj==null)
return false;
if(getClass()!=obj.getClass())
return false;
Term other=(Term)obj;
if(coefficient!=other.coefficient)
return false;
if(exponent!=other.exponent)
return false;
return true;
}
public Term(int c,int e) throws NegativeExponentException {
if(e<0)
throw new NegativeExponentException();
coefficient=c;
exponent=(coefficient==0)?1:e;
}
int coefficient,exponent;
}
public class So13408797TestCase {
#Test public void eq01() throws Exception {
assertTrue(new Term(-10,0).equals(new Term(-10,0)));
}
#Test public void eq02() throws Exception {
assertTrue(new Term(0,0).equals(new Term(0,2)));
}
private int min=Integer.MIN_VALUE;
private int max=Integer.MAX_VALUE;
}

Categories