IllegalArgumentException in parameterized test class - rules

I have a parametric test class, and I have a test method which I am expected to return IllegalArgumentException.
#RunWith(value = Parameterized.class)
public class TriangleParametrizedTest {
#Rule
public ExpectedException exception = ExpectedException.none();
enum Type {
EQUILATERAL,
NEGETIVE
};
private Type type;
private int sideA;
private int sideB;
private int sideC;
public TriangleParametrizedTest(Type type, int sideA, int sideB, int sideC) {
this.type = type;
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
}
#Parameters()
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{Type.EQUILATERAL, 5, 5, 5},
{Type.NEGETIVE, -5, 5, 5},});
}
#Test()
public void negetiveSideTest() {
Assume.assumeTrue(type == Type.NEGETIVE);
exception.expect(IllegalArgumentException.class);
Triangle trianle = new Triangle(sideA, sideB, sideC);
}
}
but I have got this error :
INitialization error : no test found matching Method negetiveSideTest ..
has anybody any solution?

When you use the #Test annotation to mark your test function, there should be no parenthesis, like so:
#Test <--- Remove the parenthesis here
public void negetiveSideTest() {
Assume.assumeTrue(type == Type.NEGETIVE);
exception.expect(IllegalArgumentException.class);
Triangle trianle = new Triangle(sideA, sideB, sideC);
}
Same goes for your #Parameters declaraion.

Related

Firebase snapshot getValue could not pars int suddenly

I hade a strange happening today with my Firebase project.
Suddenly the
AddressChatMessage chatMessage = snapshot.getValue(AddressChatMessage.class);
parsed everything ok for the AddressChatMessage except for one int.
Took me 2 hour until i tried this, setting the field to public
public int type;
Note I use this code for weeks without problem and today Android studio made some core updated to 2.3.2 and maybe that trigger this strange event.
Here´s the AddressChatMessage.java nothing strange except that the public int type cannot be private, if it is, it will be zero, that too is strange, usually Firebase give out a logcat warning when pojo parsing fails. I have 10 other modell classes like this with plenty of int´s
#IgnoreExtraProperties
public class AddressChatMessage {
// [START Firebase keys inside AddressChatMessage ]
#Exclude
public static final String TYPE = "type";
#Exclude
public static final String SENDER_ID = "senderId";
#Exclude
public static final String MESSAGE = "message";
#Exclude
public static final String FILENAME = "fileName";
#Exclude
public static final String DOWNLOAD_URI = "downloadUri";
#Exclude
public static final String TIME = "time";
// [STOP Firebase keys inside AddressChatMessage ]
public int type;
private String senderId;
private String message;
private String fileName;
private String downloadUri;
#Exclude
private long time;
#Exclude
private String messageId;
public AddressChatMessage() {
}
public AddressChatMessage(int type, String senderUid) {
this.senderId = senderUid;
this.type = type;
}
public AddressChatMessage(int type, String senderUid, String message) {
this.type = type;
this.senderId = senderUid;
this.message = message;
}
private int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDownloadUri() {
return downloadUri;
}
public void setDownloadUri(String downloadUri) {
this.downloadUri = downloadUri;
}
public long getTime() {
return time;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put(TYPE, type);
result.put(SENDER_ID, senderId);
result.put(MESSAGE, message);
result.put(FILENAME, fileName);
result.put(DOWNLOAD_URI, downloadUri);
result.put(TIME, time);
return result;
}
#Exclude
public boolean isTypeNormal() {
return getType() == ChatAdapter.MessageType.NORMAL.ordinal();
}
#Exclude
public boolean isTypeImage() {
return getType() == ChatAdapter.MessageType.IMAGE.ordinal();
}
}
When cleaning the code using Lint. Lint suggested changes like "This can be private instead of public" - I accidentally set the getType() to private access.

Orphan Removal on removing one child record, cascade="all-delete-orphan" exception

//Sensitvity Table
public class Sensitivity implements Serializable {
private static final long serialVersionUID = 1L;
private long sensitivityId;
public Set<SensitivityPattern> sensitivityPattern = new HashSet<SensitivityPattern>(0);
public Sensitivity() {
}
#Id
#SequenceGenerator(name=EntityConstants.SQ_SENSITIVITY_NAME, schema=EntityConstants.CDCIS_LAB_SCHEMA , sequenceName=EntityConstants.SQ_SENSITIVITY, allocationSize = 1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator=EntityConstants.SQ_SENSITIVITY_NAME)
#Column(name="sensitivity_id", unique=true, nullable=false, precision=10, scale=0)
public long getSensitivityId() {
return this.sensitivityId;
}
public void setSensitivityId(long sensitivityId) {
this.sensitivityId = sensitivityId;
}
#OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, mappedBy="sensitivity")
public Set<SensitivityPattern> getSensitivityPattern() {
return sensitivityPattern;
}
public void setSensitivityPattern(Set<SensitivityPattern> sensitivityPattern) {
this.sensitivityPattern = sensitivityPattern;
}
}
//SensitivityPattern
public class SensitivityPattern extends AuditableEntity implements Serializable {
private static final long serialVersionUID = 1L;
private long sensitivityPtId;
private Sensitivity sensitivity;
public SensitivityPattern() {}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "sensitivity_id")
public Sensitivity getSensitivity() {
return sensitivity;
}
public void setSensitivity(Sensitivity sensitivity) {
this.sensitivity = sensitivity;
}
#Id
#SequenceGenerator(name = EntityConstants.SQ_SENSITIVITY_PATTERN_NAME, schema = EntityConstants.CDCIS_LAB_SCHEMA, sequenceName = EntityConstants.SQ_SENSITIVITY_PATTERN, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = EntityConstants.SQ_SENSITIVITY_PATTERN_NAME)
#Column(name = "sensitivity_pt_id", unique = true, nullable = false, precision = 10, scale = 0)
public long getSensitivityPtId() {
return sensitivityPtId;
}
public void setSensitivityPtId(long sensitivityPtId) {
this.sensitivityPtId = sensitivityPtId;
}
//hash and equals overided.
}
//Code to delete Parent
#Override
public boolean saveSensitivityData(List < SensitivityDto > sensitivity, long orderId) throws LabWorkListException {
if (sensitivity != null) {
try {
for (SensitivityDto dto: sensitivity) {
if (!dto.isIsSelected()) {
//senPatternRepo.deleteById(dto.getSensitivityId());
super.delete(dto);
}else {
dto.setInvstid(orderId);
updateSensitivityPattern(dto);
super.saveOneEntity(dto);
}
}
} catch (GenericException e) {
logger.error("", e);
}
}
return true;
}
This is the code to delete one child.
/**
* To update the sensitivity data.
* #param dto
*/
private void updateSensitivityPattern(SensitivityDto dto) {
if (dto != null && dto.getSensitivityPattern() != null) {
for (SensitivityPatternDto sPattern: dto.getSensitivityPattern()) {
sPattern.setSensitivity(dto);
if (!sPattern.isIsSelected()) {
dto.setSensitivityPattern(null);
senPatternRepo.delete(sPattern.getSensitivityPtId());
}
}
}
}
Here on deleting one value in sensitivity table It throws exception
org.postgresql.util.PSQLException: ERROR: update or delete on table "lab_tb_sensitivity" violates foreign key constraint "fk_sensitivity_id" on table "lab_tb_sensitivity_pattern"
I had searched for a solution and find out orphanRemoval=true will solve this problem. Yes, its solved this problem.
But once orphanRemoval is added, when I delete a one child record its throws exception
org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: om.gov.moh.model.cdc.Sensitivity.sensitivityPattern
How can I solve this problem.
or Q2) Can I delete the Parent, it should delete all the child automatically without using orphanRemoval = true ?
You are deleting an element that is still referenced in the parent.
With orphanRemoval removing a child element is as simple as:
parent.getChildren().remove(childToBeRemoved);
and then, if this is not done within a transaction:
em.merge(parent);

JavaFX - Incompatible parameter type with using TreeView.EditEvent in lambda

In a JavaFX TreeView I'm using 'custom' classes which extend TreeItem. This makes me able to edit the items in the TreeView (I can double click them and edit the contents when running the application) but I can't seem to be able to set the .setOnEditCommit() method properly. I was hoping it'd work similar as the function in a tableview but I didn't have any luck yet.
This is my code in my controller in which I try to set the setOnEditCommit() method. In my TreeView called 'trvDivisies' I display football team divisions / competitions and one level lower I display all the teams that are in a certain division.
private void setUpTreeView() {
trvDivisies.setEditable(true);
trvDivisies.setShowRoot(false);
TreeItem<String> root = new TreeItem<>();
for (Divisie d : divisies) {
TreeItem<String> divisieTreeItem = d;
divisieTreeItem.valueProperty().set(d.getNaam());
for (VoetbalTeam vt : d.getVoetbalTeams()) {
TreeItem<String> voetbalTeamTreeItem = vt;
voetbalTeamTreeItem.valueProperty().setValue(vt.getTeamNaam());
divisieTreeItem.getChildren().add(voetbalTeamTreeItem);
}
root.getChildren().add(divisieTreeItem);
}
trvDivisies.setRoot(root);
trvDivisies.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
System.out.println(newValue);
}
});
trvDivisies.setCellFactory(TextFieldTreeCell.forTreeView());
// I get an error at the following line when compiling
trvDivisies.setOnEditCommit((TreeView.EditEvent p) -> {
TreeItem<String> selectedItem = p.getTreeItem();
if (selectedItem instanceof Divisie) {
updateDivisie((Divisie)selectedItem);
} else if (selectedItem instanceof VoetbalTeam) {
updateTeam((VoetbalTeam)selectedItem);
}
});
}
This is what my 'custom' classes look like.
public class Divisie extends TreeItem<String> {
private static int idCount = 0;
private int id;
private String naam;
private List<VoetbalTeam> voetbalTeams;
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public List<VoetbalTeam> getVoetbalTeams() {
return voetbalTeams;
}
public Divisie(int id, String naam) {
super(naam);
this.id = id;
this.naam = naam;
}
public Divisie(String naam) {
this.id = ++idCount;
this.naam = naam;
}
public void addTeam(VoetbalTeam toBeAdded) {
if (voetbalTeams == null) {
voetbalTeams = new LinkedList<>();
}
voetbalTeams.add(toBeAdded);
}
#Override
public String toString() {
return this.naam;
}
}
Second 'lower level' class
public class VoetbalTeam extends TreeItem<String> {
private static int idCount = 0;
private int id;
private String teamNaam;
private List<Speler> spelers;
public int getId() {
return id;
}
public String getTeamNaam() {
return teamNaam;
}
public List<Speler> getSpelers() {
return this.spelers;
}
public VoetbalTeam(int id, String teamNaam) {
super(teamNaam);
this.id = id;
this.teamNaam = teamNaam;
}
public VoetbalTeam(String teamNaam) {
super(teamNaam);
this.id = ++idCount;
this.teamNaam = teamNaam;
}
public void addSpeler(Speler nieuweSpeler) {
if (spelers == null) {
spelers = new LinkedList<>();
}
this.spelers.add(nieuweSpeler);
}
#Override
public String toString() {
return this.teamNaam;
}
}
When trying to run the application WITH the .setOnEditCommit() method I get an error saying:
Error:(97, 37) java: incompatible types: incompatible parameter types in lambda expression
I was hoping you guys can tell me what I need to change my TreeView.EditEvent lambda to or help me find an easier solution.
For a TreeView<T>, the signature of setOnEditCommit is
void setOnEditCommit(EventHandler<TreeView.EditEvent<T>> value)
Since you have (apparently) a TreeView<String>, you need
trvDivisies.setOnEditCommit((TreeView.EditEvent<String> p) -> {
// ...
});
Or, of course, you can just let the compiler do the work for you:
trvDivisies.setOnEditCommit(p -> {
// ...
});

how to fix this reflection code in java?

i am trying to make a test runner first class is test runner and second one is class that testet and last one is my main page.. i want to reach the tester method with method invoke but this is not working.
public class tester {
public tester()
{
}
#Test
public void testTopla(){
int sayi1 = 10;
int sayi2 = 20;
int gercekSonuc = 30;
//
islem isl = new islem(sayi1, sayi2);
int sonuc = isl.topla();
Assert.assertTrue("Sonucta Hata Var", sonuc == gercekSonuc);
}
and this is what i am testing
public class islem {
private int sayi1;
private int sayi2;
public islem(){
}
public islem(int sayi1, int sayi2){
this.sayi1 = sayi1;
this.sayi2 = sayi2;
}
public int getSayi1() {
return sayi1;
}
public void setSayi1(int sayi1) {
this.sayi1 = sayi1;
}
public int getSayi2() {
return sayi2;
}
public void setSayi2(int sayi2) {
this.sayi2 = sayi2;
}
public int topla(){
return this.sayi1 + this.sayi2;
}
and this
public class Deneme1UI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = Deneme1UI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Class hilmi = tester.class;
tester obj = new tester();
for(Method method : hilmi.getDeclaredMethods())
{
method.invoke(obj);
}
look at this:
http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#invoke%28java.lang.Object,%20java.lang.Object...%29
the first parameter of the invoke() function needs to be an instance of the reflected class
in your case an instance of the class tester
you will have to create an instance of the tester class before you can invoke its methods

collections.binarySearch() is not working with comparable

After sorting List in ascending and descending order i want to invoke binarySearch method.
But it not working as i have implemented comparable.
class Student implements Comparable<Student>{
private int id;
private String name;
public Student(int id, String name){
this.id = id;
this.name = name;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
#Override
public int compareTo(Student o) {
int j = o.getId();
int result = this.id - j;
return result;
}
}
public class CollectionSearchDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student(3, "ouier"));
list.add(new Student(2, "fdgds"));
list.add(new Student(7, "kiluf"));
list.add(new Student(1, "6trfd"));
list.add(new Student(8, "hjgas"));
list.add(new Student(5, "ewwew"));
Collections.sort(list, new Comparator<Student>() {
#Override
public int compare(Student arg0, Student arg1) {
return arg0.getId() - arg1.getId();
}
});
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Student student = (Student) iterator.next();
System.out.print(student.getId()+":"+student.getName()+" ");
}
System.out.println("\nSorting in reverse order:");
// Collections.reverse(list);
Comparator<Student> collections = Collections.reverseOrder();
Collections.sort(list, collections);
Iterator iterator1 = list.iterator();
while(iterator1.hasNext()){
Student student = (Student) iterator1.next();
System.out.print(student.getId()+":"+student.getName()+" ");
}
System.out.println("I want to do searching ");
System.out.println("\n2 is at:"+Collections.binarySearch(list, 2, new Student()));
// facing exception at this line.I don't know what to use as argument of binarySearch() method.
}
}
I could have done this by implementing comparator but i have such requirement in my project
Please guide me.
From documentation of Collections.binarySearch:
The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined.

Resources