How to JUnit test an add method for a custom made ArrayList? - arrays

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().

Related

#Cacheable in Spring does not understand dynamically assigned values

I need to dynamically assign values of cacheResolver for #Cacheable in runtime because cacheResolver has the same value for #Cacheable in every method. Hence, I use Spring AOP to dynamically assign the value but then Spring does not recognize the newly added value for cacheResolver.
Seems that AOP load #Cacheable value at the beginning.
Anyone knows how to make it work?
My AOP code:
#Aspect
#Component
#Order(1)
public class CacheableAspect {
#Pointcut("#annotation(org.springframework.cache.annotation.Cacheable)")
public void cacheablePointCut() {}
#Before("cacheablePointCut()")
public void addCacheableResolver(JoinPoint joinPoint) {
Annotation cacheableAnnotation = getCacheableAnnotation(joinPoint);
Object handler = Proxy.getInvocationHandler(cacheableAnnotation);
Field f;
try {
f = handler.getClass().getDeclaredField("memberValues");
} catch (NoSuchFieldException | SecurityException e) {
throw new IllegalStateException(e);
}
f.setAccessible(true);
Map<String, Object> memberValues;
try {
memberValues = (Map<String, Object>) f.get(handler);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
memberValues.put("cacheResolver", "cacheableResolver");
}
private Annotation getCacheableAnnotation(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
return method.getAnnotation(Cacheable.class);
}
}
My #Cacheable code in which i want cacheResolver is dynamically assigned a value:
#Cacheable(value = "test")
public int test() {
System.out.println("xxx");
return 10;
}
OK, so you are trying to dynamically change an annotation representation in the JVM during runtime. Not only is that ugly, but it probably does not work as you hope it would. It seems you found out that specific annotations are represented by a dynamic proxy instance during runtime, then you are successfully manipulating one of its field values. But annotations are meant to be immutable, aber depending on when e.g. Spring scans the annotations while wiring the application, your approach to modify the proxy fields later, while being a nice try, just comes too late.
How about a more canonical approach to use multiple cache managers and/or a resolver which dynamically does what you need to begin with? As much as I love AOP, it is not the answer to everyhing.
By the way, even though your aspect is kind of useless in this case, at least we can use it as an example of how to bind annotation values to advice methods parameters, i.e. you do not need to fetch the annotation from the method by reflection next time you write an aspect:
#Pointcut("#annotation(cacheable)")
public void cacheablePointCut(Cacheable cacheable) {}
#Before("cacheablePointCut(cacheable)")
public void addCacheableResolver(JoinPoint joinPoint, Cacheable cacheable) {
Object handler = Proxy.getInvocationHandler(cacheable);
// (...)
}

Silverlight Unit Testing multiple initializations with same tests

I have an object with lots of properties that I would like to test. I have written a TestMethod for each property, but the problem is that many of the properties manipulate the others when they are set. What I need is to be able to set up my test object, manipulate one of the variables, run the tests, reset the object to its original state, then repeat the process. That way, I can avoid having so much redundancy.
I looked into using a Data Driven approach (which is a perfect solution to this problem), but that doesn't seem to be available with the Silverlight Test Framework, since I can't find a way to use the DataSource attribute. I thought about trying to see if I could get access to the DataSource through the traditional MSTest framework, but alas, I only have Visual Studio Express.
I've thought to try to look into creating a custom test harness to see if that could solve this problem, but I thought I'd ask around for suggestions first.
Maybe I should just suck it up and write up all of the different configurations as separate TestInitialize Methods and comment out the ones I don't need as I go.
Any help would be greatly appreciated.
Update/Clarification:
Here is an example of how the object to be tested works. Say you have a shape with a position coordinate and coordinates for each side. When you Update the coordinates of the position or one of the sides, all other coordinates must be updated as well.
This is the functionality that is under test. What I would like to do is be able to set up multiple initializations (through ClassInitialize or what have you) where I would set up the initial value of my object and a mock containing the expected test results, then alter one of the properties in question. Something like this (this is for illustration only, so please ignore any poor practices xD):
// class under test (mock has the same properties & constructor)
public class MySquare
{
public Vector2 XYPosition;
public int Width;
public int Height;
public float TopSidePosition;
public float RightSidePosition;
...
public MySquare(float x, float y, int width, int height)
{
// set up all properties
}
}
// test object container
public class Container
{
public static MySquare square;
public static MySquareMock squareMock;
}
// desired test class initializations (it would be nice to be able to run each of these
// as well as the TestMethods and then reset to the next TestSetupClass)
[TestClass]
public class TestSetupClass1
{
[ClassInitialize]
public void SetupTest()
{
// set up initial value and expected result
Container.square = new MySquare(0, 0, 5, 5);
Container.squareMock = new MySquareMock(1, 1, 5, 5);
Container.square.XYPosition = new Vector2(1, 1);
}
}
[TestClass]
public class TestSetupClass2
{
[ClassInitialize]
public void SetupTest()
{
// set up initial value and expected result
Container.square = new MySquare(0, 0, 5, 5);
Container.squareMock = new MySquareMock(1, 0, 5, 5);
Container.square.RightSidePosition = 6;
}
}
// test methods
[TestClass]
public class TestMethods
{
[TestMethod]
public void TestPosition()
{
Assert.AreEqual(Container.squareMock.XYPosition, Container.square.XYPosition);
}
[TestMethod]
public void TestTopSidePosition()
{
Assert.AreEqual(Container.squareMock.XYTopSidePosition, Container.square.TopSidePosition);
}
// test method for each property
}
I didn't find a completely automated way of achieving my original goal, but I did come up with something pretty easy.
First, I created a singleton TestManager class to handle nearly all of my test setup, so that I only need one line in my MainPage (the test page) class. Within the TestManager, I added a string variable that I assign a name of a TestSetup class too from the MainPage.
Then, I created another TestClass called TestSetupClass and gave two static fields:
private static Type childType;
private static TestSetupClass childInstance;
In its constructor, I compare the underlying type to the class name specified in the TestManager and set the childType and childInstance if they match:
Type thisType = GetType().UnderlyingSystemType;
if (thisType.Name.Equals(TestManager.Instance.SetupClassName))
{
childType = thisType;
childInstance = this;
}
Next, I added a virtual method to the TestSetupClass with an AssemblyInitialize attribute. All of my setup classes inherit from TestSetupClass and override this method. Within the method, I use the childType to get MethodInfo for the child's overridden implementation of the method and invoke it using the childInstance:
MethodInfo childSetup = childType.GetMethod("Setup");
childSetup.Invoke(childInstance, null);
And voila! When you want to run a specific setup before running all the tests, you just specify its class name in the MainPage using the TestManager.
I know there are a few more places where I could have made this better, but it works, so what can you do.

c# returning arrays via properties

Id like to firstly apologise for what may appear to be a stupid question but im confused regarding the following.
Im writting a class library which will not be running on the UI thread. Inside the CL i need an array which im going populate with data received from a stored procedure call. I then need to pass this data back to the UI thread via an event.
Originally i was going to write the following.
public class ColumnInformation
{
public string[] columnHeaderNames;
public string[] columnDataTypes;
}
but im pretty sure that would be frowned upon and i instead should be using properties.
public class ColumnInformation
{
public string[] columnHeaderNames {get; set;}
public string[] columnDataTypes {get; set;}
}
but then i came across the following.
MSDN
so am i correct in assuming that i should actually declare this as follows:
public class ColumnInformation
{
private string[] _columnHeaderNames;
public Names(string[] headerNames)
{
_columnHeaderNames = headerNames;
}
public string[] GetNames()
{
// Need to return a clone of the array so that consumers
// of this library cannot change its contents
return (string[])_columnHeaderNames.Clone();
}
}
Thanks for your time.
If your concern is the guideline CA1819: Properties should not return arrays,
It will be same whether you are exposing Array as a Public Field, or Property (making readonly does not matter here). Once your original Array is exposed, its content can be modified.
To avoid this, as the link suggest, make Field private, and return Clone from the Getter.
However major concern is that there may be multiple copies of your array if retrieved many times. It is not good for performance and synchronization.
Better solution is ReadOnlyCollection.
Using ReadOnlyCollection, you can expose the collection as read only which cannot be modified. Also any changes to underlying collection will be reflected.

Importing a class with a specific parameter

I got a ViewModel which I export with MEF. I'd like this ViewModel to be initialized differently each time it's being imported, according to an enum/specific object parameter that will be provided to it.
I've been reading a little on the subject and I found that maybe this -
http://msdn.microsoft.com/en-us/library/ee155691.aspx#metadata_and_metadata_views
would be able to fit my needs, but I'm not sure that this would be the best way to do it.
Another method I've been thinking about is importing the class normally, and then once I've an instance, to call a special initialization method that would receive my parameter. However this doesn't seem like a classic MEF implementation, and maybe losses some of its "magic".
I'm hoping someone would be able to point out for me what would be the recommended method to achieve this.
Thanks!
A workaround is exporting a factory that creates instances of your type. While this means you cannot directly import thos instances, it does have the benefit that the logic to create them is the responsability of the factory so users of the class do not have to know about it:
public class ServiceWithParameter
{
public ServiceWithParameter( int a )
{
this.a = a;
}
private readonly int a;
}
[Export]
public class ServiceWithParameterFactory
{
public ServiceWithParameterFactory()
{
instance = 0;
}
public ServiceWithParameter Instance()
{
return new ServiceWithParameter( instance++ );
}
private int instance;
}
//now everywhere you need ServiceWithParameter:
[Import]
ServiceWithParameterFactory serviceFactory;
var instanceA = serviceFactory.Instance(); //instanceA.a = 0
var instanceB = serviceFactory.Instance(); //instanceB.a = 1
A more extensible way is telling the container you have a factory and an example is presented here: http://pwlodek.blogspot.com/2010/10/mef-object-factories-using-export.html

C# setting form.visible = false inside a method?

hi i have this lines of code that i cant make it work
the goal is simple setting the form1 to visible = false
public static void DoActions(string Cmd){
if(Cmd == true)
{
MainForm.Visible = false;
}
}
but i keep on having this error
An object reference is required for
the non-static field, method, or
property
usually i set the called methond to static.. so the error will go away
but on this case how do i do it?
thanks for any help guys
'System.Windows.Forms.Control.Invoke(System.Delegate)'
This is happening because DoActions is a static method rather than an instance method, however MainForm is an instance field / property. The distinction is that instance methods operate on an instance of the class on which they are defined, wheras static methods do not.
This means that wheras instance methods are able to access properties, fields and methods of their containing class through the this keyword, for example:
// Instance field
Form1 MainForm;
void InstanceMethod()
{
Form1 frm = this.MainForm;
}
You cannot do the same thing from inside a static method (think about it, what instance would it operate on?). Note that C# will implicitly assume the use of the this keyword in places where it makes sense (so the above example could have been written as Form1 frm = MainForm).
See C# Static Methods for an alternative explanation of static vs instance methods (this is an important concept in object oriented programming that you should take the time to understand properly).
In your example you probably want to change DoActions to an instance method (by removing the static declaration):
public void DoActions(string Cmd)
{
if(Cmd == true)
{
this.MainForm.Visible = false;
}
}
This will allow it to access the instance MainForm field / property, however this may cause problems elsewhere in your code in places where you attempt to call DoActions from another static method without supplying an object instance.
Set form opacity and showintaskbar property in property window:
this.Opacity = 0;
this.ShowInTaskbar = false;
Your method is static - and so cannot access MainForm.
Make your method non-static if it is not required to be so.
public void DoActions(string Cmd)
{
if(Cmd == true)
{
MainForm.Visible = false;
}
}
If it is required, then create a static field in your class and ensure it is set before this method runs.

Resources