assertEquals compares objects id and not the content of the object? - junit

I wanted to test my insert method. The insert method simply adds the object to the list. However, when I used assertEquals, it seemed to be comparing objects and not the content of the objects.
Is there a way to compare the elements of the user defined objects that is stored in an ArrayList?
#Test
public void testInsert() {
// Method answer
Interval newInterval = new Interval(1, 20);
ArrayList<Interval> emptyInterval = new ArrayList<Interval>();
ArrayList<Interval> returnedAnswer = Solution.insert(emptyInterval, newInterval);
// Expected answer
ArrayList<Interval> expected = new ArrayList<Interval>();
//expected.add(newInterval); // This will pass
expected.add(new Interval(1, 20)); // This will fail
assertEquals(expected, returnedAnswer);
}

assertEquals tests equality of objects by calling their equals method. This means that the objects must have a sufficient implementation of that method. It looks like Interval does not have it. Therefore you have to implement Interval.equals(Object).
You can use Hamcrest matchers if you don't want to override equals. But you need the reflectEquals matcher of NitorCreations matcher library, too.
assertThat(returnedAnswer, contains(
reflectsEquals(new Interval(1, 20))));
Maybe AssertJ provides a similar assert, but you have to look for yourself, because I'm rarely using AssertJ.

Related

Invalid Use Of Matchers Exception with toString() [duplicate]

I have this TestNG test method code:
#InjectMocks
private FilmeService filmeService = new FilmeServiceImpl();
#Mock
private FilmeDAO filmeDao;
#BeforeMethod(alwaysRun=true)
public void injectDao() {
MockitoAnnotations.initMocks(this);
}
//... another tests here
#Test
public void getRandomEnqueteFilmes() {
#SuppressWarnings("unchecked")
List<Filme> listaFilmes = mock(List.class);
when(listaFilmes.get(anyInt())).thenReturn(any(Filme.class));
when(filmeDao.listAll()).thenReturn(listaFilmes);
List<Filme> filmes = filmeService.getRandomEnqueteFilmes();
assertNotNull(filmes, "Lista de filmes retornou vazia");
assertEquals(filmes.size(), 2, "Lista não retornou com 2 filmes");
}
And I'm getting a "org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:" in the call of listAll() method in this code:
#Override
public List<Filme> getRandomEnqueteFilmes() {
int indice1, indice2 = 0;
List<Filme> filmesExibir = new ArrayList<Filme>();
List<Filme> filmes = dao.listAll();
Random randomGenerator = new Random();
indice1 = randomGenerator.nextInt(5);
do {
indice2 = randomGenerator.nextInt(5);
} while(indice1 == indice2);
filmesExibir.add(filmes.get(indice1));
filmesExibir.add(filmes.get(indice2));
return filmesExibir;
}
I'm prety sure I'm missing something here but I don't know what it is! Someone help?
when(listaFilmes.get(anyInt())).thenReturn(any(Filme.class));
There's your problem. You can't use any in a return value. any is a Matcher—it's used to match parameter values for stubbing and verification—and doesn't make sense in defining a return value for a call. You'll need to explicitly return a Filme instance, or leave it null (which is the default behavior, which would defeat the point of stubbing).
I should note that it's often a good idea to use a real List instead of a mock List. Unlike custom code you've developed, List implementations are well-defined and well-tested, and unlike mock Lists a real List is very unlikely to break if you refactor your system under test to call different methods. It's a matter of style and testing philosophy, but you may find it advantageous just to use a real List here.
Why would the above rule cause that exception? Well, this explanation breaks some of Mockito's abstractions, but matchers don't behave like you think they might—they record a value onto a secret ThreadLocal stack of ArgumentMatcher objects and return null or some other dummy value, and in the call to when or verify Mockito sees a non-empty stack and knows to use those Matchers in preference to actual argument values. As far as Mockito and the Java evaluation order are concerned, your code looks like the following:
when(listaFilmes.get(anyInt())).thenReturn(null);
when(filmeDao.listAll(any())).thenReturn(listaFilmes); // nonsense
Naturally Mockito sees an any matcher, and listAll doesn't take an argument, so there are 0 matchers expected, 1 recorded.

Argument(s) are different! Wanted: Actual invocation has different arguments:

ServiceClass:
public void createManualEvaluationReductionChangeHistory(Long key, String accountId, RegisterReductionPerFunction registerReductionPerFunction, String languageCode, String comments, String pagRedFlag) {
ProfessionalCustomerHistory professionalCustomerHistory = new ProfessionalCustomerHistory();
professionalCustomerHistory.setDescription(comments);
professionalCustomerHistory.setReductionCategory(registerReductionPerFunction.getReductionCategoryCode());
professionalCustomerHistory.setReductionType(registerReductionPerFunction.getReductionTypeCode());
professionalCustomerHistory.setValidityId(registerReductionPerFunction.getValidityId().longValue());
professionalCustomerHistory.setReductionPercentage(reductionCategoryService.getReductionPercentage(languageCode,
registerReductionPerFunction.getReductionCategoryCode(), registerReductionPerFunction.getReductionTypeCode()));
professionalCustomerHistory.setTotalReduction(professionalCustomerHistory.getReductionPercentage());
professionalCustomerHistory.setPagFixedReductionFlag(pagRedFlag);
setCommonHistoryDetails(professionalCustomerHistory, Constants.NO, accountId, key, Constants.HISTORY_TYPE_REDUCTIONS);
professionalCustomerHistoryDlService.create(professionalCustomerHistory);
}
Junit Test:
#Test
public void createManualEvaluationReductionChangeHistory() {
ProfessionalCustomerHistory professionalCustomerHistory = new ProfessionalCustomerHistory();
RegisterReductionPerFunction registerReductionPerFunction = new RegisterReductionPerFunction();
professionalCustomerHistory.setValidityId(1L);
registerReductionPerFunction.setValidityId(1);
professionalCustomerHistory.setProfCustomerId(PROF_CUST_ID);
professionalCustomerHistory.setHistoryType("RD");
professionalCustomerHistory.setEditedBy(ACCOUNT_ID);
professionalCustomerHistory.setHistoryDate(new Date());
professionalCustomerHistory.setNoDeleteFlag("N");
professionalCustomerHistory.setReductionPercentage(null);
professionalCustomerHistory.setTotalReduction(null);
professionalCustomerHistory.setDescription(COMMENTS);
Mockito.when(reductionCategoryService.getReductionPercentage(LANGUAGE_CODE, null, null)).thenReturn(null);
profCustomerHistoryService.createManualEvaluationReductionChangeHistory(PROF_CUST_ID, ACCOUNT_ID.toString(), registerReductionPerFunction, LANGUAGE_CODE, COMMENTS, null);
Mockito.verify(reductionCategoryService).getReductionPercentage(LANGUAGE_CODE,null,null);
Mockito.verify(professionalCustomerHistoryDlService).create(professionalCustomerHistory);
}
When i am testing it getting below error.
Argument(s) are different! Wanted:
Actual invocation has different arguments:
But i see all the parameters are exact the same. what might be causing the issue?
ProfessionalCustomerHistory is a DB entity, i dont have equals and hashcode
Assuming that its only your 2nd verify that fails, this is the problem.
Currently you create a different ProfessionalCustomerHistory object in your test and in your logic. They might have the same content but without properly implemented equals and hashcode methods, the default implementation in java only cares about the object reference.
If you use an IDE it probably has some generate method that lets you generate the proper equals and hashCode methods.
If you only want to validate that the correct method is called, without caring about the exact content, you could use:
Mockito.verify(professionalCustomerHistoryDlService)
.create(Mockito.any(ProfessionalCustomerHistory.class));
If you can not or do not want to change the ProfessionalCustomerHistory class, you could use an ArgumentCaptor and compare the distinct fields afterwards.

Return different values each time from jMockit expectation

I have a unit test where I am mocking java.net.URI class. Further, I am creating a jMockit NonStrictExpectation where I am expecting invocation of URI.getPath() and returning a particular string.
The code being tested invokes URI.getPath() twice, where I need to send a different string each time.
Here is my actual method under test:
public void validateResource() {
// some code
URI uri = new URI(link1.getHref());
String path1 = uri.getPath();
// some more code
uri = new URI(link2.getHref());
String path2 = uri.getPath();
}
Here is the unit test code:
#Mocked URI uri;
#Test
public void testValidateResource() {
new NonStrictExpectations() {
{
// for the first invocation
uri.getPath(); returns("/resourceGroup/1");
// for the second invocation [was hoping this would work]
uri.getPath(); returns("/resource/2");
}
};
myObject.validateResource();
}
Now, I want "/resource/2" to be returned from my expectation when the URI.getPath() is called second time. But it always hits the first expectation and returns "/recourceGroup/1". This is my problem.
How do I make it happen? I can't really use StrictExpectations due to a number of reasons, and will have to stick with NonStrictExpectations.
Seems like you just need to list uri.getPath() once, and use the varargs version of returns...something like this:
uri.getPath(); returns("/resourceGroup/1", "/resourceGroup/2");
This is according to the documentation, anyway...I have not tested it myself.
Multiple consecutive values to return can be recorded for an expectation, by calling the returns(v1, v2, ...) method. Alternatively, the same can be achieved by assigning the result field with a list or array containing the consecutive values.

AS3 - Returning a property of a class rather than the class itself

In ActionScript 3, there are some classes that will represent a value rather than the class itself. It's hard to explain properly what I mean, so take this example:
var str:String = "something";
var mc:MovieClip = new MovieClip();
trace(str); // something
trace(mc); // [object MovieClip]
You'll notice that the first trace outputs a value, rather than [object String]. Ontop of this, I can still make use of methods of String, like this:
var ar:Array = str.split('s');
Even though in a way you could almost read the above as:
"something".split('s');
I have a class AvLevelData that has some methods that deal with level data (which is essentially a String). At the moment there is a property data:String which represents the core level data.
The question I have is - can I replicate the behaviour of String in that when I trace or assign an instance of AvLevelData, the result is actually the String data.
For example, at the moment I need to go:
var levelData:AvLevelData = new AvLevelData();
trace(levelData.data);
To get the data. I instead want to be able to simply do the following:
var levelData:AvLevelData = new AvLevelData();
trace(levelData); // some level data string
Is this possible?
If you wan't your object to trace out your own fabricated string then you must implement a toString() function on your AvLevelData class.
In your example above, the MovieClip trace outputs: [Object MovieClip]; this comes from the default toString() implementation for Object (found on Object.prototype) . Note, you cannot override toString() as it only exists on the prototype of Object (remnants of the AS2/Javascript world), all you need to do is provide your own implementation with the same name. For instance:
public function toString():String {
return "MyCustomObjectString";
}
Some of the most basic types - String, int, Number, uint, Boolean, to name a few - are not classes / objects per se, they are primitives. In some languages there is a wrapper class available for some of these so they can be treated like objects, though Flash doesn't do this so much from my experience.
Probably the best way to answer your question is to make a toString() method for your AvLevelData class:
public function toString():String {
return data;
}
Any time you treat a class as a string (such as by putting it in trace()), flash (and many other languages) try to call toString() on the object. Typically this results in a string that's not helpful. But if you define your own toString() method, you can control what string gets output.
Another option is to simply do:
trace(AvLevelData.data);
Since that variable is a string, it should trace just fine.

Creating a "true" HashMap implementation with Object Equality in ActionScript 3

I've been spending some of my spare time working a set of collections for ActionScript 3 but I've hit a pretty serious roadblock thanks for the way ActionScript 3 handles equality checks inside Dictionary Objects.
When you compare a key in a dictionary, ActionScript uses the === operator to perform the comparison, this has a bit of a nasty side effect whereby only references to the same instance will resolve true and not objects of equality. Here's what I mean:
const jonny1 : Person = new Person("jonny", 26);
const jonny2 : Person = new Person("jonny", 26);
const table : Dictionary = new Dictionary();
table[jonny1] = "That's me";
trace(table[jonny1]) // traces: "That's me"
trace(table[jonny2]) // traces: undefined.
The way I am attempting to combat this is to provide an Equalizer interface which looks like this:
public interface Equalizer
{
function equals(object : Object) : Boolean;
}
This allows to to perform an instanceOf-esq. check whenever I need to perform an equality operation inside my collections (falling back on the === operator when the object doesn't implement Equalizer); however, this doesn't get around the fact that my underlying datastructure (the Dictionary Object) has no knowledge of this.
The way I am currently working around the issue is by iterating through all the keys in the dictionary and performing the equality check whenever I perform a containsKey() or get() operation - however, this pretty much defeats the entire point of a hashmap (cheap lookup operations).
If I am unable to continue using a Dictionary instance as the backing for map, how would I go about creating the hashes for unique object instances passed in as keys so I can still maintain equality?
How about you compute a hash code for your objects when you insert them, and then look them up by the hash code in your backing dictionary? The hashcode should compare === just fine. Of course, that would require you to have a Hashable interface for your object types instead of your Equalizer interface, so it isn't much less work than you are already doing, but you do get the cheap lookups.
How about rather doing this:
public interface Hashable {
function hash():String;
}
personally, I ask myself, why you want to do this ... hashing objects to obtain keys makes little sense if they are mutable ...
also, you might consider using a different approach, as for example this factory:
package {
public class Person {
/**
* don't use this!
* #private
*/
public function Person(name:String, age:int) {
if (!instantiationAllowed)
throw new Error("use Person.getPerson instead of constructor");
//...
}
private static var instantiationAllowed:Boolean = false;
private static var map:Object = {};
private static function create(name:String, age:int):Person {
instantiationAllowed = true;
var ret:Person = new Person(name, age);
instantiationAllowed = false;
}
public static function getPerson(name:String, age:int):Person {
var ageMap:Array = map[name];
if (ageMap == null) {
map[name] = ageMap = [];
return ageMap[age] = Person.create(name, age);
}
if (ageMap.hasOwnProperty(age))
return ageMap[age];
return ageMap[age] = Person.create(name, age);
}
}
}
it ensures, there's only one person with a given name and age (if that makes any sense) ...
Old thread I know, but still worth posting.
const jonny1 : Person = new Person("jonny", 26); const jonny2 : Person = new Person("jonny", 26);
is creating two completely different objects that will not compare using ==, guess I don't see why it's any more of a road block because of as3
The problem with AS3/JavaScript/EcmaScript is not that they create two different, equivalent objects.
The problem is that they cannot equate those two equivalent objects--only identity works, since there is no equals or hashCode methods that can be overriden with class-specific comparison logic.
For Map implementations such as dynamic Object or Dictionary, this means that you have to either use Strings or references as keys: you cannot recover objects from a map using different but equivalent objects.
To work around that problem, people either resort to strict toString implementations (for Object maps) which is undesirable, or to instance control for Dictionaries, as in #back2dos example, which introduces different problems (Also, note that #back2dos solution does not really guarantee unique Person instances since there is a time window during which asynchronous threads will be allowed to instantiate new Persons).
#A.Levy's solution is good except that in general, hashCodes are not strictly required to issue unique values (they are meant to map entries to buckets allowing for fast lookups, wherein fine-grained differentiation is done through equals method).
You need both a hashCode and an equals method, e.g.
public interface IEquable
{
function equals(object : Object) : Boolean;
function hash():String;
}
In any programming language,
const jonny1 : Person = new Person("jonny", 26);
const jonny2 : Person = new Person("jonny", 26);
is creating two completely different objects that will not compare using ==, guess I don't see why it's any more of a road block because of as3