A fairly straightforward question regarding EasyMock. Read up a bunch of resources but not sure what I am missing:
The following snippet is creating a unit test using Test-ng:
#Test(groups = "unit")
public class SchoolTestEasyMock {
#Test
public void test1() {
School mockSchool = EasyMock.createNiceMock(School.class);
EasyMock.replay(mockSchool);
System.out.println(mockSchool.getSchoolNumber());
}
}
Let's assume the School class has a simple getter 'getSchoolNumber' that returns an Integer.
The snippet above is printing a 'null' to the console. Since I'm creating a 'nice' mock shouldn't the 'getSchoolNumber' return a default value of 0? Am I missing something while creating the nice mock?
From the documentation:
If you would like a "nice" Mock Object that by default allows all method calls and returns appropriate empty values (0, null or false), use niceMock() instead.
As Integer is an object, the default value is null.
If you change the return type of the method to int, the value will be 0 as expected.
Related
I want to get rid of clone() method.
For the below class sonar (static code check tool) was complaining that
I should not directly expose an internal array of the object as one can change the array after the method call which in turn changes the object's state. It suggested to do a clone() of that array before returning so that object's state is not changed.
Below is my class...
class DevicePlatformAggregator implements IPlatformListings{
private DevicePlatform[] platforms = null;
public DevicePlatform[] getAllPlatforms() throws DevicePlatformNotFoundException {
if (null != platforms) {
return platforms.clone();
}
List<DevicePlatform> platformlist = new ArrayList<DevicePlatform>();
..... // code that populates platformlist
platforms = platformlist.toArray(new DevicePlatform[platformlist.size()]);
return platforms;
}
}
However I don't think its good to clone as its unnecessary to duplicate the data.
There is nothing similar to Collections.unmodifiableList() for array
I can not change the return type of the method getAllPlatforms() to some
collection as it is an interface method
I am not a Java guru but I am pretty confident that you are out of luck here. There is no way to make a primitive array immutable apart from creating an array of 0 elements.
Making it final won't help cause only the reference pointing to it would be immutable.
As you already said the way to go in obtaining an unmodifiable list would be to use Collections as in the following example:
List<Integer> contentcannotbemodified= Collections.unmodifiableList(Arrays.asList(13,1,8,6));
Hope it helps.
I implemented my custom ArrayList using a resizeable Array, and I would like to unit test my add method to check if the right value getting inserted to the right position. My add method looks like this:
public class MyArrayList<T> implements ArrayListInterface {
private int max=20;
private int index = 0;
private int[] a = new int[max];
#Override
public void add(int value) {
if(index>max-1) {
resize();
}
a[index] = value;
index++;
}
I am aware, I could just make my method boolean and check what the method returns, but I would like to check that the right value added to the right position. My problem is that my Array is private, and that way it is only possible to reach its value through a getter. Is it a good solution to make a getter for my Array, and compare that to the actual result of the test, or what would be the best solution to test this method?
I have checked couple of other stackoverflow questions in the same topic, but I couldn't find any solution for my problem.
Add a get() (get(position), getLast(), etc.) method to your class and test using this method. Unit tests should exercise the class through its interfaces, without caring about the internal implementation. Any other class that will interact with your MyArrayList will do so through add() and get().
I would like to auto-generate a method's return values in a non-deterministic manner, i.e. with every call/test run to I expect a method to return random value. For the moment it returns always default values of the method calls:
public interface IReturn
{
bool BoolMethod();
int IntMethod();
}
[Fact]
public void AllReturnsFromAutofixtureMethodsAreFalse()
{
IFixture fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
IEnumerable<IReturn> theBools = fixture.CreateMany<IReturn>();
Assert.True(theBools.All(tb => tb.BoolMethod() == false));
Assert.True(theBools.All(tb => tb.IntMethod() == 0));
}
In questions like this one can find a way how to achieve similar thing for properties, however not methods. Any idea?
I haven't used AutoFixture with NSubstitute customization, however by analogy to Moq library, It seems that AutoConfiguredNSubstituteCustomization class should be used to achieve advanced AutoFixture faking behavior such that you want to. Using it you can auto-generate results from stubbed methods, as well as it is possible to create mock objects chains, injecting freezed objects into chain, an so on.
i m writing test using easymock, and i created the following mock object for my test,
auditor = createMock(Auditor.class);
auditor.start(isA(Audit.class)); //record
replay(auditor);
expect(auditor.getAudit("my-process")).andReturn(null);
replay(auditor);
Auditor class has a method 'start(Audit.class)', i recorded it first, then stub its other method 'getAudit()', then replay them all. however it complained:missing behavior definition from previous call start(isA(Audit.class)), what did i do wrong here? thanks,
You have specified the mock behavior for "auditor.start(...)" method incorrectly. Assuming it returns void, one way to do it would be:
#Test
public void testAuditor() {
Auditor auditor = EasyMock.createMock(Auditor.class);
auditor.start(Audit.class);
EasyMock.expectLastCall(); //record
EasyMock.expect(auditor.getAudit("my-process")).andReturn(null);
EasyMock.replay(auditor);
//rest of your test code
}
I would like to create a new array with a given type from a class object in GWT.
What I mean is I would like to emulate the functionality of
java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)
The reason I need this to occur is that I have a library which occasionally needs to do the following:
Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();
This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.
I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation, there exists an inaccessible static method for creating a class object for an array.
Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.
In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.
If you are cool with creating a seed array of the correct type, you can use jsni along with some knowledge of super-super-source to create arrays WITHOUT copying through ArrayList (I avoid java.util overhead like the plague):
public static native <T> T[] newArray(T[] seed, int length)
/*-{
return #com.google.gwt.lang.Array::createFrom([Ljava/lang/Object;I)(seed, length);
}-*/;
Where seed is a zero-length array of the correct type you want, and length is the length you want (although, in production mode, arrays don't really have upper bounds, it makes the [].length field work correctly).
The com.google.gwt.lang package is a set of core utilities used in the compiler for base emulation, and can be found in gwt-dev!com/google/gwt/dev/jjs/intrinsic/com/google/gwt/lang.
You can only use these classes through jsni calls, and only in production gwt code (use if GWT.isProdMode()). In general, if you only access the com.google.gwt.lang classes in super-source code, you are guaranteed to never leak references to classes that only exist in compiled javascript.
if (GWT.isProdMode()){
return newArray(seed, length);
}else{
return Array.newInstance(seed.getComponentType(), length);
}
Note, you'll probably need to super-source the java.lang.reflect.Array class to avoid gwt compiler error, which suggests you'll want to put your native helper method there. However, I can't help you more than this, as it would overstep the bounds of my work contract.
The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.
public class Foo extends Bar<Baz> {
public Foo()
{
super(new Baz[0]);
}
...
}
Baz:
public abstract class Baz<T>
{
private T[] emptyArray;
public Baz(T[] emptyArray)
{
this.emptyArray = emptyArray;
}
...
}
In this case the Bar class can't directly create new T[10], but we can do this:
ArrayList<T> al = new ArrayList<T>();
// add the items you want etc
T[] theArray = al.toArray(emptyArray);
And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).
I had to do something similar, I found it was possible using the Guava library's ObjectArrays class. Instead of the class object it requires a reference to an existing array.
T[] newArray = ObjectArrays.newArray(oldArray, oldArray.length);
For implementing an array concatenation method, I also stepped into the issue of missing Array.newInstance-method.
It's still not implemented, but if you have an existing array you can use
Arrays.copyOf(T[] original, int newLength)
instead.