Java / JUnit - comparing two polynomial objects - java

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;
}

Related

Trying to do JUnit Test but Getting some error

Below is the JUnit Tester Class
import java.lang.reflect.Method;
public class SimpleUnitTester {
public int execute(Class clazz) throws Exception {
int failedCount = 0;
// your code
execute(Reflection.class);
Reflection reflection = null;
try {
reflection = (Reflection) clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().startsWith("test") && method.getReturnType() == boolean.class) {
try {
boolean returnedValue = ((Boolean) method.invoke(reflection)).booleanValue();
if (!returnedValue) {
failedCount++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return failedCount;
}
}
Below is the Reflection Class
public class Reflection {
public void go() {
}
public boolean testA() {
return true;
}
public void foo() {
}
public void bar() {
}
public int testB() {
return 0;
}
public boolean testC() {
return false;
}
public boolean testD() {
return false;
}
public boolean testE() {
return true;
}
public boolean anotherTest() {
return false;
}
}
I want to do test like, In the Reflection class if methods Start with keyword "test" and If Method have boolean returnType then it will Qualify the test. If the test is failed then Return the test faild value. But I am getting Null in Output.

How to implement and fire an event when a change occurs in a property of `T` in `List<T>` within the owning class in Java

Any clue if it is possible to convert code below to Java (Android) from C#?
It is based on my prev.question
How to implement and fire an event when a change occurs in a property of `T` in `List<T>` within the owning class
public class ItemPropertyChangedNotifyingList<T> : IList<T>, INotifyPropertyChanged where T : INotifyPropertyChanged
{
private List<T> _listImplementation = new List<T>();
public void Add(T item)
{
item.PropertyChanged += ItemOnPropertyChanged;
_listImplementation.Add(item);
}
private void ItemOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(sender, e);
}
public IEnumerator<T> GetEnumerator()
{
return _listImplementation.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_listImplementation).GetEnumerator();
}
public void Clear()
{
_listImplementation.ForEach(x => x.PropertyChanged -= ItemOnPropertyChanged);
_listImplementation.Clear();
}
public bool Contains(T item)
{
return _listImplementation.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_listImplementation.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
item.PropertyChanged -= ItemOnPropertyChanged;
return _listImplementation.Remove(item);
}
public int Count => _listImplementation.Count;
public bool IsReadOnly => false;
public int IndexOf(T item)
{
return _listImplementation.IndexOf(item);
}
public void Insert(int index, T item)
{
item.PropertyChanged += ItemOnPropertyChanged;
_listImplementation.Insert(index, item);
}
public void RemoveAt(int index)
{
_listImplementation.RemoveAt(index);
}
public T this[int index]
{
get => _listImplementation[index];
set => _listImplementation[index] = value;
}
public event PropertyChangedEventHandler PropertyChanged;
}
Have we use PropertyChangeListener for this task? Like it is shown here.
public FocusManagerListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if ("focusOwner".equals(propertyName) {
...
} else if ("focusedWindow".equals(propertyName) {
...
}
}
...
}
I just ported ItemPropertyChangedNotifyingList to ItemChangeList.
In code, I changed this part.
Used 'ArrayList' to hold elements instead of 'List` in C#
In copyTo, I used Java 8 Stream. Since you tag 'android', I used Lightweight-Stream-API to achieve same feature of copyTo.
Java doesn't support get, set syntax, i divide to two methods.
import com.annimon.stream.Stream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ItemChangedList<T> {
private List<T> _listImplementation = new ArrayList<>();
private List<OnPropertyChangedObserver<T>> _changedObserverList = new ArrayList<>();
public static final String ITEM_ADDED = "bbed36af-0b7b-4e53-abc9-02d6a14d7f34";
public static final String ITEM_REMOVED = "7390116e-586d-4e62-9343-5b82b0a8c6c5";
public void add(T item) {
sendPropertyChanged(item, ITEM_ADDED);
_listImplementation.add(item);
}
public Iterator<T> iterator() {
return _listImplementation.iterator();
}
public void clear() {
for (T item : _listImplementation) {
sendPropertyChanged(item, ITEM_REMOVED);
}
_listImplementation.clear();
}
public boolean contains(T item) {
return _listImplementation.contains(item);
}
public void copyTo(T[] array, int arrayIndex) {
// Using https://github.com/aNNiMON/Lightweight-Stream-API
_listImplementation.addAll(Stream.of(array).skip(arrayIndex).toList());
// Traditional Java way
// _listImplementation.addAll(Arrays.stream(array).skip(arrayIndex).collect(Collectors.toList()));
}
public boolean remove(T item) {
sendPropertyChanged(item, ITEM_REMOVED);
return _listImplementation.remove(item);
}
public int count() {
return _listImplementation.size();
}
public boolean isReadOnly() {
return false;
}
public int indexOf(T item) {
return _listImplementation.indexOf(item);
}
public void insert(int index, T item) {
sendPropertyChanged(item, ITEM_ADDED);
_listImplementation.add(index, item);
}
public void removeAt(int index) {
_listImplementation.remove(index);
}
public T get(int index) {
return _listImplementation.get(index);
}
public void set(int index, T item) {
_listImplementation.set(index, item);
}
public void addObserver(OnPropertyChangedObserver<T> observer) {
_changedObserverList.add(observer);
}
public void removeObserver(OnPropertyChangedObserver<T> observer) {
_changedObserverList.remove(observer);
}
public void clearObserver() {
_changedObserverList.clear();
}
private void sendPropertyChanged(T item, String args) {
for (OnPropertyChangedObserver<T> observer : _changedObserverList) {
observer.onChanged(item, args);
}
}
public interface OnPropertyChangedObserver<T> {
void onChanged(T item, String args);
}
}
Other way is extends ArrayList instead _listImplementation. it can be provide more functionally. Personally, I prefer this way. Gist
Edit-1) Oh, i forget add args in OnPropertyChangeObserver.
Edit-2) Let Kotlin optimize this! Gist

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?

javaCC inserts non-wanted statements

I've got the following javacc grammar.
The rule UnaryExpr creates some anonymous classes implementing java.util.function.Predicate<>
options {
static=false;
DEBUG_PARSER=false;
IGNORE_CASE=true;
JDK_VERSION="1.8";
}
(...)
private Predicate<SAMRecord> UnaryExpr(): { }
{
(
<DUPLICATE> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getDuplicateReadFlag();}
};}
| <UNMAPPED> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getReadUnmappedFlag();}
};}
| <FAILSVENDORQUALITY> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getReadFailsVendorQualityCheckFlag();}
};}
| <PROPERPAIR> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getReadPairedFlag();}
};}
)
}
when I'm generating the code using javacc 7.0.2, the generated java code contains some extra statements that break the code {if ("" != null). In the java file, instead or my original code:
#Override public boolean test(final SAMRecord rec) {return rec.getDuplicateReadFlag();}
I've got:
#Override public boolean test(final SAMRecord rec) { {if ("" != null) return rec.getDuplicateReadFlag();}}
How can I fix this ? Thanks .
That's a rather annoying behaviour.
Could you live with this?
private Predicate<SAMRecord> UnaryExpr(): {
class A implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getDuplicateReadFlag(); } }
class B implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getReadUnmappedFlag(); } }
class C implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getReadFailsVendorQualityCheckFlag(); } }
class D implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getReadPairedFlag(); } }
}
{
( <DUPLICATE> { return new A() ; }
| <UNMAPPED> { return new B() ; }
| <FAILSVENDORQUALITY> { return new C() ; }
| <PROPERPAIR> { return new D() ; }
)
}

How to test Binary Tree using Junit?

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.

Categories