I am doing an assignment that requires me to create the code that will make this run with no errors or failures. This is only one test case:
Toy t1 = new Toy(1000121, "Red Bike", 3, 98.90);
Toy t2 = new Toy(1000123, "Colouring Book", 4, 19.89);
Toy t3 = new Toy(1000128, "Skateboard", 5, 149.99);
Toy t4 = new Toy(1000127, "SpongeBob DVD", 3, 14.99);
Toy t5 = new Toy(1000130, "Bike Helmet", 1, 18.99);
Toy t6 = new Toy(1000125, "Toy car", 10, 3.99);
Toy t7 = new Toy(1000129, "Ball", 2, 5.59);
Toy t8 = new Toy(1000189, "Teddy Bear", 3, 10.79);
Toy[] listofToy1 = { t1, t2 };
Child c1 = new Child("James", 1, listofToy1);
assertTrue(c1.getChildToy().length == 2 && c1.getChildToy()[0] != t1 && c1.getChildToy()[1] != t2);
assertTrue(c1.getChildToy().length == 2 && c1.getChildToy()[0].getToyName().equals("Red Bike") && c1.getChildToy()[1].getToyName().equals("Colouring Book"));
assertTrue(c1.getChildToy().length == 2 && c1.getChildToy()[0].getToyQuantity() == 3 && c1.getChildToy()[1].getToyQuantity() == 4);
My question is how does the first assertTrue even work? Am I missing something?
You can infer what each method means by what its called. For reference, the getChildToy method will return an array of Toy objects. The toy objects are from the created Toys from line 1-8
To me it looks like Child c1 is created with an array of toys that include t1 and t2 in index 0 and 1, respectively. So how can c1.getChildToy()[0] not equal t1 from the first assert?
And if c1.getChildToy()[0] is not equal to t1, how can c1.getChildToy()[0].getToyName().equals("Red Bike") from the second assert be true?
Any help will be appreciated thank you.
Edit: I tried system.out.println.
System.out.println(c1.getChildToy()[0].getToyInformation());
System.out.println(c1.getChildToy()[1].getToyInformation());
console showed this:
(1000121, "Red Bike", 3, 98.90)
(1000123, "Colouring Book", 4, 19.89)
which is a match to line 1 and 2
P.S. getToyInformation method just puts the info from the toy object into a formatted string
You appear to think
==means "same content".It doesn't. It means 'same reference'.
What the method is testing is that the
Childconstructor takes its toy input (the third argument) and clones every toy object.Imagine I build a house.
I then build the exact same house next door. Same layout. Walls painted the same colour. I even decorate them identically.
Are they the same house? No. But, they are the same design.
house1 == house2would be false because it's not the same house.house1.equals(house2)is true, though.We can trivially see this in java:
We made 2 strings here. However, they so happen to have the same content. They're like the 2 identical houses.
Note that the whole setup here (arrays, mutable objects, defensive cloning) is 20 years out of date code style, I don't know what course or tutorial this is, but, oof. It's very out of date.