EasyMock - Mock a class having other class object and .class as parameters - java

I am currently using EasyMock and trying a lot to fix my problem.
Let me explain you in the simple words, Totally I have 5 classes.
Main.java
A.java
B.java
C.java
Result.java
From Main.java I am calling a method of A.java
objectOfA.someMethod("String",objectofB, C.class);
While Mocking...
expect( objectofA.someMethod( "given some String", Prepared some dummy object of B and passing , C.class ) ).andReturn( objectofResult ).anyTimes();
While I am running the application its giving AssersionError.
My Questions:
In the expect method > while calling objectofA.someMethod(), In the second parameter I am creating one dummy object of B, actually B has nearly 10 variables and among them one will be generated randomly, but while creating the dummy object I am giving some value of my own, will it be a problem ?
3rd parameter, we have to pass C.class, How can we pass this ?
Finally in andReturn() I am passing objectofResult class, do I need to parpare the dummy object of Result in this case ? because in Result.java we have nearly 20 variables and its really difficult for me to guess the values.
In Result.java I just need to verify a single String variable value.
I am trying a lot since 3 days, can someone help me to fix this please.

We can't tell you what is "right" for your code; because we don't have the full picture (and you should not expect that somebody will spent his time to dive into all your code if you would have posted it).
So, for your questions:
1) +2) I think you are getting it backward. The point is: you tell EasyMock about the invocations that your "code under test" should make.
This means: you tell EasyMock that someMethod should be invoked; and EasyMock will check if the actual invocation matches your specification.
So, it really depends on your implementation of your B class. If the B object that your actual code passes with someMethod() is equal to the B object that you provide in the EasyMock staging; than all is fine. But if they are not equal, then EasyMock will complain. You can change that for example by using matchers, like
EasyMock.expect(
yourMock.someMethod(
eq("string to match"), anyObject(B.class), ...)
(where eq, anyObject being static methods in EasyMock).
But the problem there is: if you use matchers; you have to use matchers on all your arguments. And (for the moment); I am not aware of a matcher that would work for the "class" argument. So, for now I can only advise to do something like:
EasyMock.expect(
yourMock.someMethod("string to match", expectedB, C.class))
where "expectedB" is a B object that you setup in advance; so that it matches what is created by your code under test. In order to get there, you will have to make sure that your B class as a "good" equals() method.
3) Again; the question what your "dummy result" is capable of; depends on how your code under test will be using it.
Example: assume that your code under test will invoke .toString() on that result object. Then you might want to prepare for that; for example by making that result object ... be another mock; that expects calls to toString().
Long story short: you use EasyMock to specify everything that you expect to "come out" of your class under test; and to control everything that "flows into" that class under test.

Related

When are dot operators required?

When calling a method, I get that you have to use instanceName.method() or className.method(). However, in some cases the instanceName or className is omitted in the code and just method() is written.
Programming language is Java. Just covering this for the AP Computer Science test and I have relatively limited knowledge of coding outside of the parameters of the course so a easy to understand explanation would be greatly appreciated.
My book says something about client programs but I'm not exactly sure what it means (both in general and about client programs specifically).
I'll put my explanation as simply as possible - Usually you would use instanceName.method() when trying to effect the variables within a class. For example a "Cat" object, you could make a cat - Cat catOne = new Cat() and then use its methods catOne.setName("Kitty");. This will set this objects name to "Kitty", leaving all other cat objects with the ability to have their own unique name.
Using className.method() is done when using a static method within a class, eg public static int method(), and then using it in another class. This does not require you to instantiate an object for that class, and can use them willingly. For example, having a class called MathConstants and using something like MathConstants.getPi() ( Sorry for the crude example ).
When methods are called like methodName() , this means that the method is located within the class itself. Usually we use this , as in this.methodName(), but just using methodName() is okay.
Hope that is easy to understand

Ruby Class definition explanation for a java developer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am a java developer and am having hard time understanding this Ruby code, can someone please explain this code in java terms? I can understand the methods part (defs) but the belongs_to part is what confusing me
module Test
class Signature < Base
belongs_to :recipient, :class_name => 'Test::UserInformation'
belongs_to :sd_file, :class_name => 'Test::TransportFile',
:foreign_key => 'reference_id'
def sd_status
sd_file.nil? ? nil : sd_file.Status
end
def sd_sent_on
sd_file.nil? ? nil : sd_file.sent
end
def sd_received_on
sd_file.nil? ? nil : sd_file.received
end
def self.find_information(options={})
unless (start_date = options.delete(:start_date)).blank? ||
(end_date = options.delete(:end_date)).blank?
date_conditions = ' AND ' +
'(requested_at > ?) AND ' +
'(requested_at < ?)'
end
The key thing here is to realize that (almost) everything in Ruby is a script, (almost) everything in Ruby is a message send ("virtual method call" in Java-speak), and (almost) everything in Ruby is an object.
In Java, the only executable code is inside method definitions. Everything else are just declarations, directives to the compiler to create some compiler-internal data structure. A class declaration isn't executed at runtime, it is interpreted at compile time by the compiler, which then generates the corresponding class structure, methods, fields, etc.
Not so in Ruby. The content of a file is just a script that gets executed top to bottom. That's why you can, for example, have stuff like this:
if OS.windows?
class Foo
end
else
class Bar
end
end
Likewise, the body of a module or class definition is just a script, which allows you to have stuff like this:
if OS.windows?
def foo
end
else
def bar
end
end
So, as you can see, really almost everything is a script, in particular, the body of a class definition is just a script that gets executed from top to bottom, just like any other script.
By the way, since the class definition is dynamically executed at runtime and not statically interpreted by the compiler, the same goes for the superclass definition in a class definition: it is, in fact, just an arbitrary Ruby expression that returns an object that is an instance of Class, it doesn't necessarily have to be a static constant class, i.e. you can write something like this:
class Foo < if rand < 0.5 then String else Array end
end
# Yes, I am aware that this makes zero sense. Here is a more sensible example:
class Point < Struct.new(:x, :y)
end
# `Struct` is a class whose `::new` method returns a class
class Search < R '/search'
end
# This is an example from the Camping web microframework:
# `Search` is a controller which is bound to the URI route `/search`
In case you are wondering: if a class definition is just a piece of code, does it return anything? And the answer is "Yes, it does!" In fact, everything in Ruby returns something, everything is an expression in Ruby. There are no statements. Only expressions. A class definition evaluates to the value of the last expression that is evaluated inside the class definition. Typically, the last expression that is evaluated inside a class definition is a method definition (yes, a method definition is an expression just like any other, and thus also has a return value), and a method definition evaluates to the name of the method being defined, expressed as a Symbol
Also, almost everything is an object: there is a top-level global object which doesn't have a name but is usually called main (because that's what its to_s and inspect return). Everything you run at the top-level in a script happens with self (this in Java-speak) being bound to main. And classes are also objects, they are instances of the Class class. Within a class definition body, self is bound to the class that is being defined.
Now, on to "almost everything is a message send": usually, whenever you see something being "done" in Ruby, it is the result of a message send: 1 + 2 is actually 1.+(2), !false is actually false.!, foo.bar = baz is actually foo.bar=(baz), ary[idx] is actually ary.[](idx), ary[idx] = val is actually ary.[]=(idx, val) and so on and so forth.
belongs_to is no different: it is actually a message send to self, which in the context of a class definition is the class being defined. In other words, it's just calling a "class method". (Note: there aren't really class methods in Ruby, every method is an instance method. As we have already established, classes are objects like any other object, so they can have instance methods like any other object, there is no need for a special "class method" or "static method" construct!)
Let's start with an easier example:
class Foo
attr_reader :bar
end
Again, attr_reader is a message send to self, which is Foo in this case. attr_reader just generates an attribute reader (a "getter" in Java-speak). And it looks a bit like this (don't worry if you don't fully grasp Ruby Reflection yet, you should be able to follow along anyhow):
class Class # in reality, it is defined in `Module`, a superclass of `Class`
def attr_reader(name)
define_method(name) do
instance_variable_get(:"##{name}")
end
end
end
By the way: def is not a message send, it is a builtin keyword. But there is a corresponding method that can be used instead, which you see being used above: Module#define_method
In fact, Ruby doesn't even have constructors! new is just a "class method", and it looks pretty much like this:
class Class
def new(*args, &block)
new_obj = allocate
new_obj.initialize(*args, &block)
return new_obj
end
end
There are a few subtleties here, such as initialize being private by default, so that in reality we need to use reflection to circumvent access restrictions, but that's the gist of it.
Oh, and since I just mentioned private: that's a method, too, not a keyword that is interpreted as an instruction for the compiler.
So, to recap, where do we stand: a class definition is just a piece of code, method definitions are just expressions that get executed. But since a class definition is just a piece of code, there can be arbitrary code in there, including message sends ("method calls" in Java-speak). belongs_to is just a message send (method call) to the class itself, i.e. the method is defined somewhere up in the inheritance chain of the class object itself (not to be confused with the inheritance chain of instances of the class!)
But the really important takeaway is this: it is just a method call. Nothing scary. Nothing magical. Nothing special.
Now, what does this method call do?
It is part of a popular ORM library for Ruby called ActiveRecord, and it sets up an association between self (i.e. the class whose definition the call appears in) and another class whose name is provided as an argument (or to be more precise: since ActiveRecord relies a lot on conventions, the name of the class can be derived from the argument). From this association between Ruby classes, the ActiveRecord ORM will automatically deduce corresponding relations between the database tables backing those classes.
Explaining how exactly that works would amount to writing a full tutorial on ActiveRecord, which a) is just too much for a Stack Overflow answer, and b) other people have already done much better than me. But I got the impression anyway that you didn't so much want to know how belongs_to works internally, but rather how a method call can appear in what your Java-trained mind is used to being just "dead code" that doesn't get executed. And the solution to that riddle is simply: it isn't dead code and it does get executed.
belongs_to may seem like a very magical piece of ruby code, that connects your model to another, using SQL table associations.
But all it does is takes in a few hash parameters, creating series of dynamic methods.
Lets take apart
belongs_to :sd_file, class_name: 'Test::TransportFile', foreign_key: 'reference_id'
belongs_to - A methods to set up an association
sd_file - What method will be used to acess it:
Test::Signature.first.sd_file
class_name - option to specify which ruby class to load. sd_file will point to Test::TransportFile. Usually this is done automatically by rails if everything adheres to conventions. But you can specify manually
foreign_key - Key in the table which ties the two records together. This is either in Test::TransportFile or in Test::Signature (I can't remember off the top of my head). And it will tie in with the id in another table.

Unit testing method parameter verification best practice

What is the best practice for verifying a method call with complex parameters when unit testing?
Say I'm testing a function like this:
class ClassA {
ClassB dependency;
void someFunction(SomeInputForA input) {
// do some thing
dependency.anotherFunction(differentInput);
}
}
The two options that I can think of for verifying that someFunction calls anotherFunction with the proper input are:
A) do a verify on the mock of dependency for calling anotherFunction
unitUnderTest.dependency = mockClassB;
InputClass expectedDifferentInput = ... ;
verify(mockClassB).anotherFunction(expectedDifferentInput);
B) do an argument captor on the call of anotherFunction and assert the properties
unitUnderTest.dependency = mockClassB;
ArgumentCaptor<InputClass> captor = ArgumentCaptor.for(InputClass.class);
verify(mockClassB).anotherFunction(captor.capture());
InputClass capturedInput = captor.getValue();
assertEquals(value, capturedInput.param1);
// and more asserts afterwards
Is there a suggested path here? I'd lean towards the captor method because it feels more rigorous and is not relying on objects equals implementations being proper.
Thoughts?
Is differentInput computated off input?
If so then your B) is the better way to go as you are saying for Input A, you expect ClassA to change this to expectedDifferentInput and want to verify the delegating class (ClassB) is called. You are verifying the transformation of the input and delegating logic of ClassA.
If differentInput has no relation to input then you don't need to use the captor as really you are just checking delegation.
Any public caller to someFunction on ClassA shouldn't need to know about ClassB so it can be said both methods A) and B) are actually white box testing, in this case and so you might as well use the captors anyway. As you vary your input to someFunction, captors may also help you to identify edge cases if differentInput is computed off input.
You can always use matchers on the object passed into mockClassB.anotherFunction(). For example, if you want to compare fields on an object, you can write:
Matcher<YourClass> yourMatcher = Matchers.hasProperty("yourProperty", Matchers.equals(whatever));
verify(mockClassB).anotherFunction(argThat(yourMatcher));
I prefer this way, since you can share syntax for the when and the verify for the matchers and you can combine any combination of matchers. You just need to include the latest mockito and hamcrest libraries to get this to work.
I've used argument captors but VERY sparingly. The biggest issue you run into is that this route creates fragile unit tests. And no one is happy when they make a small change to a class and then find themselves struggling with unit tests in calling classes that shouldn't have been affected.
That being said, absolutely you have to eventually ensure that correct calls are made. But if you rely on an equals override working, then you are relying on that class having an equals method that works, and this is then part of that class's contract (and unit tested in that class) which is reasonable.
So that's why I'd vote for keeping it simple and just using verify. Same thing in the end, but your unit test is just less fragile.

Java & Mockito - passing an argument to a method AND capturing the result

I'm trying to fix some existing junit/mockito tests that I've had to alter due to a re-write to use Dao's.
So I have this argument captor :-
ArgumentCaptor<CustomerDao> customerDaoCaptor = ArgumentCaptor.forClass(CustomerDao.class);
and I've used this approach before to get the (customer) object so that I can perform more tests on it. I would usually use it like this :-
verify(customerDao, times(1)).saveOrUpdate(customerDaoCaptor.capture());
so that I can then run tests like :-
Customer customerActual = (Customer) customerDaoCaptor.getAllValues().get(0);
assertEquals("PRE", customerActual.getExistingCustomer());
However in this instance I'm not calling the saveOrUpdate method (that the captor is bound to), but another Dao method that takes a unique key as a parameter that ultimately updates the customer record by using sql - ie it doesnt use the parent object's (Hibernate) saveOrUpdate method.
I know that I can test that its called, eg :-
inOrder.verify(customerDao, times(1)).updateRegisterStatusToCurrentByCustomerNumber(CUSTOMER_NUMBER);
so I'm trying to somehow assign/bind the captor to the 'updateRegisterStatus....' method, but I cant seem to find a way to do it, mainly because that method must take a string param, customer_number.
So in essence I'm trying to do this :-
inOrder.verify(customerDao, times(1)).updateRegisterStatusToCurrentByCustomerNumber(CUSTOMER_NUMBER).customerDaoCaptor.capture()
which obviously doesn't work...
As a lot of googling hasn't helped me, I'm guessing that I'm doing it completely wrong.
Update - #SpaceTrucker
I've tried the following code as you suggested :-
CapturingMatcher<String> capturingMatcher = new CapturingMatcher<String>();
verify(customerDao, times(1)).updateRegisterStatusToCurrentByCustomerNumber(
argThat(
org.hamcrest.Matchers.allOf(capturingMatcher, org.hamcrest.Matchers.notNullValue())
)
);
List<String> values = capturingMatcher.getAllValues();
based on my Dao implementation :-
public void updateRegisterStatusToCurrentByCustomerNumber(String customerNumber)
and it does pass the test successfully, in that it doesn't fail, but it doesnt do everything what I need it to. The ideal goal here is to somehow get an object representing the updated customer object - eg :-
Customer customerActual = (Customer) values.get(0);
assertEquals("value", customerActual.getExistingCustomer());
However the values object is empty and on debugging the test I can confirm that the method in question is being called.
Apologies in advance if there's something trivial that I've missed here, and once again, thanks for all your help!
This problem seems to more difficult than first thought about. See below for more details on this.
The Matcher instance Mockito does need to see has to implement the CapturesArguments interface. So the solution is to implement an AndMatcher that will delegate to its child matchers and implements CapturesArguments. It will delegate to all child matchers that also implement CapturesArguments when CapturesArguments.captureFrom(Object). Please note that CapturesArguments is a Mockito internal interface.
The following solution does not work,
because the Matcher instance Mockito sees, doesn't implement the CapturesArguments interface and therefore won't delegate the argument capturing to the CapturingMatcher.
The ArgumentCaptor uses a CapturingMatcher internally. So you could use Mockito.argThat with a combined matcher that will consist of a CapturingMatcher and any other matcher you like.
For example given the interface
public interface ProductService {
List<Product> getProductsForCategory(Category category);
}
then we can do the following:
import org.hamcrest.Matchers;
// ...
CapturingMatcher<Category> capturingMatcher = new CapturingMatcher<Category>();
Mockito.verify(productService).getProductsForCategory(Mockito.argThat(Matchers.allOf(capturingMatcher, Matchers.notNullValue())));
List<Category> values = capturingMatcher.getAllValues();
You could also implement your own ArgumentCaptor with a capture method that will take an additional matcher instance.
Your question isn't entirely clear, but I'm getting the following points from it:
You have a mock of a CustomerDao.
Your test (indirectly) calls the updateRegisterStatusToCurrentByCustomerNumber() method of this mock, passing a String identifier to it.
updateRegisterStatusToCurrentByCustomerNumber() does something internally to a Customer object.
You want to test things about the Customer object in question.
If these are correct, then you have a fundamental misunderstanding of how mocks work. That internal code that does something to a Customer object? In this test, that code doesn't exist. It's never called. The mock version of CustomerDao responds to your updateRegisterStatusToCurrentByCustomerNumber() call by simply returning what your test setup code told it to, whether that's null, a carefully crafted sample object, or another mock. It never invokes the actual CustomerDao code because the whole point of a mock is to make your test not be dependent on that code, so that bugs in that code don't cascade test failures throughout the dependency tree.
To test the internal behavior of CustomerDao.updateRegisterStatusToCurrentByCustomerNumber(), you will need to create separate tests that directly call CustomerDao methods on a non-mock CustomerDao, with everything else being mocks.

Basic Java homework

I know this is simple but I don't really understand the question...
Assume the signature of the method xMethod is as follows.
Explain two different ways to invoke xMethod:
public static void xMethod(double[] a)
I thought to invoke a method you just do:
xMethod(myarray);
What could it mean by asking two different ways? Maybe I'm just looking into the question too much.
For kicks, show your professor this:
XClass.class.getMethod("xMethod", a.getClass()).invoke(null, a);
Then tell them the two answers are
XClass.xMethod(a);
//and
xObject.xMethod(a); //this is bad practice
If this is for a first time java class, my guess is he is looking for these 2 cases:
//the one you have, using a precreated array
double[] myArray = {1.1, 2.2, 3.3}
xMethod(myarray);
//and putting it all together
xMethod(new double[]{1.1, 2.2, 3.3});
Basically illustrating you can make an array to pass, or simply create one in the call.
Just a guess though
You could invoke it either by calling it on a class, or via an instance of that class.
Foo.xMethod(a);
or:
Foo foo = new Foo();
foo.xMethod(a);
The first approach is prefered, but the second one will compile and run. But be aware that it is often considered a design flaw in the language that the second approach is allowed.
static methods are not bound to the construction of the class.
The method above can be called either by constructing the class or just by using the namespace:
Classname myclass = new Classname();
myclass.xMethod(myarray);
or you could just do:
Classname.xMethod(myarray);
as you see, you don't have to construct the class in order to use the method. On the other hands, the static method can't access non-static members of the class.
I guess that's what the question meant by 2 different ways...
There is only one valid way to do this:
YourClass.xMethod(myDoubleArray);
But, you can write non-totally-correct Java:
YourClass instance = new YourClass();
instance.xMethod(myDoubleArray);
This will work, but is considered as wrong. The Java compiler will even complain about it. Because a there is no need of invoking a static method by creating an instance of the class. Static means that the method is instance independent. Invoking it through an instance is pointless and confusing.
Later on, you will see that there is a second correct way of doing it, ie "reflection". But that is an advanced topic, so I assume you are not supposed to know this already.

Categories

Resources