How to expect on method calls that has inline new instance creations in easymock - junit4

We have following code structure in our code
namedParamJdbcTemplate.query(buildMyQuery(request),new MapSqlParameterSource(),myresultSetExtractor);
and
namedParamJdbcTemplate.query(buildMyQuery(request),new BeanPropertySqlParameterSource(mybean),myresultSetExtractor);
How can I expect these method calls without using isA matcher?
Assume that I am passing mybean and myresultSetExtractor in request for the methods in which above code lies.

you can do it this way
Easymock.expect(namedParamJdbcTemplateMock.query(EasyMock.anyObject(String.class),EasyMock.anyObject(Map.class),EasyMock.anyObject(ResultSetExtractor.class))).andReturn(...);
likewise you can do mocking for other Methods as well.
hope this helps!
good luck!

If you can't use PowerMock to tell the constructors to return mock instances, then you'll have to use some form of Matcher.
isA is a good one.
As is anyObject which is suggested in another answer.
If I were you though, I'd be using Captures. A capture is an object that holds the value you provided to a method so that you can later perform assertions on the captured values and check they have the state you wanted. So you could write something like this:
Capture<MapSqlParameterSource> captureMyInput = new Capture<MapSqlParameterSource>();
//I'm not entirely sure of the types you're using, but the important one is the capture method
Easymock.expect(namedParamJdbcTemplateMock.query(
EasyMock.anyObject(Query.class), EasyMock.capture(captureMyInput), EasyMock.eq(myresultSetExtractor.class))).andReturn(...);
MapSqlParameterSource caughtValue = captureMyInput.getValue();
//Then perform your assertions on the state of your caught value.
There are lots of examples floating around for how captures work, but this blog post is a decent example.

Related

How to use recursive_update

I just started to use DBx::Class and begun slightly to understand, but it's complex.
I want to call "recursive_update" but I was not able to manage how I can use it.
If I understand the documentation right, I have to include it in the .../My/Schema.pm which was create by DBIx::Class::Schema::Loader?
__PACKAGE__->load_namespaces(default_resultset_class => '+DBIx::Class::ResultSet::RecursiveUpdate');
When I want to update the data I use the ResultSet with the relationships.
my $result = $schema->resultset('Table')->find($id});
$result->recursive_update({
'rel_table' => [....),
});
unfortunately I got an error:
Can't locate object method "recursive_update" via package My::Schema::Result::Table"
Where is my fault?
recursive_update has to be called on a ResultSet object, not a Result object.
You might want to add a helper method to your Result base class (if you already have one else create it, as it makes sense for many things) which gets a ResultSet restricted to the Result object it is called on and calls recursive_update on it.

Dont understand the concept of extends in URL.openConnection() in JAVA

Hi I am trying to learn JAVA deeply and so I am digging into the JDK source code in the following lines:
URL url = new URL("http://www.google.com");
URLConnection tmpConn = url.openConnection();
I attached the source code and set the breakpoint at the second line and stepped into the code. I can see the code flow is: URL.openConnection() -> sun.net.www.protocol.http.Handler.openConnection()
I have two questions about this
First In URL.openConnection() the code is:
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}
handler is an object of URLStreamHandler, define as blow
transient URLStreamHandler handler;
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right? But there are a lot classes who implement this methods in sun.net.www.protocol (like http.Hanlder, ftp.Handler ) How should the code know which "openConnection" method it should call? In this example, this handler.openConnection() will go into http.Handler and it is correct. (if I set the url as ftp://www.google.com, it will go into ftp.Handler) I cannot understand the mechanism.
second. I have attached the source code so I can step into the JDK and see the variables but for many classes like sun.net.www.protocol.http.Handler, there are not source code in src.zip. I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip? Where can I find a comprehensive version of source code?
Thanks!
First the easy part:
... I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip?
Two reasons:
In the old days when the Java code base was proprietary, this was treated as secret-ish ... and not included in the src.zip. When they relicensed Java 6 under the GPL, they didn't bother to change this. (Don't know why. Ask Oracle.)
Because any code in the sun.* tree is officially "an implementation detail subject to change without notice". If they provided the code directly, it helps customers to ignore that advice. That could lead to more friction / bad press when customer code breaks as a result on an unannounced change to sun.* code.
Where can I find a comprehensive version of source code?
You can find it in the OpenJDK 6 / 7 / 8 repositories and associated download bundles:
http://hg.openjdk.java.net/jdk6/jdk6 - http://download.java.net/openjdk/jdk6/
http://hg.openjdk.java.net/jdk7/jdk7 - http://download.java.net/openjdk/jdk7/
http://hg.openjdk.java.net/jdk8/jdk8
Now for the part about "learning Java deeply".
First, I think you are probably going about this learning in a "suboptimal" fashion. Rather than reading the Java class library, I think you should be reading books on java and design patterns and writing code for yourself.
To the specifics:
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right?
At the point that the handler calls than method, it is calling it on an instance of the subclass. So finding the right method is handled by the JVM ... just like any other polymorphic dispatch.
The tricky part is how you got the instance of the sun.net.www.protocol.* handler class. And that happens something like this:
When a URL object is created, it calls getURLStreamHandler(protocol) to obtain a handler instance.
The code for this method looks to see if the handler instance for the protocol already exists and returns that if it does.
Otherwise, it sees if a protocol handler factory exists, and if it does it uses that to create the handler instance. (The protocol handler factory object can be set by an application.)
Otherwise, searches a configurable list of Java packages to find a class whose FQN is package + "." + protocol + "." + "Handler", loads it, and uses reflection to create an instance. (Configuration is via a System property.)
The reference to handler is stored in the URL's handler field, and the URL construction continues.
So, later on, when you call openConnection() on the URL object, the method uses the Handler instance that is specific to the protocol of the URL to create the connection object.
The purpose of this complicated process is to support URL connections for an open-ended set of protocols, to allow applications to provide handlers for new protocols, and to substitute their own handlers for existing protocols, both statically and dynamically. (And the code is more complicated than I've described above because it has to cope with multiple threads.)
This is making use of a number of design patterns (Caches, Adapters, Factory Objects, and so on) together with Java specific stuff such as the system properties and reflection. But if you haven't read about and understood those design patterns, etcetera, you are unlikely to recognize them, and as a result you are likely to find the code totally bamboozling. Hence my advice above: learn the basics first!!
Take a look at URL.java. openConnection uses the URLStreamHandler that was previously set in the URL object itself.
The constructor calls getURLStreamHandler, which generates a class name dynamically and loads, and the instantiates, the appropriate class with the class loader.
But URLStreamHandler is a abstract class and method openConnection()
is not implement in it so when handler calls this method, it should go
to find a subclass who implement this method, right?
It has to be declared or abstract or implemented in URLStreamHandler. If you then give an instance of a class that extends URLStreamHandler with type URLStreamHandler and call the openConnection() method, it will call the one you have overriden in the instance of the class that extends URLStreamHandler if any, if none it will try to call the one in URLStreamHandler if implemented and else it will probably throw an exception or something.

Assigning to a stub class method in Moles while using partial stubs

I've seen this question regarding partial stubs, but it does not quite tell me what I need to know.
I understand that, if I am using a Moles stub for a class (let's say, for DataService, I'm using SDataService), I can set the CallBase property to true so that, if there is no delegate for a particular method, the base implementation's method will be called. Great, but how do I assign a delegate to a particular method in this case?
If there is no way to do that, say I have an interface IDataService that I stub using SIDataService. I can easily assign a delegate to a method here. But, how do I tell it to call the corresponding method on DataService (an implementation of IDataService) if there is no delegate for a given method?
Thank you!
Edit:
I see now that the method needs to be virtual to be overridden in the first scenario above. I don't think that makes a whole lot of sense, but it is what it is.
So, focusing on the second scenario, would I have to create a Behavior? (And why isn't there one already for stubs like there is for moles?) Or is there a simpler way?
Delegates (detours) are set to stubs types the same way as mole types. For example, SIDataService.GetMemberProfile() is configured to return a mock object like this:
var memberMock = new Member() { Firstname="Joe", LastName="Schmoe" };
var stub = new SIDataService();
stub.GetMemberProfileMember = i => memberMock;

Is there any way to create a fake from a System.Type object in FakeItEasy?

Is there any way to create a fake from a System.Type object in FakeItEasy? Similar to:
var instance = A.Fake(type);
I try to write a fake container for AutoFac that automatically return fakes for all resolved types. I have looked in the code for FakeItEasy and all methods that support this is behind internal classes but I have found the interface IFakeObjectContainer that looks pretty interesting, but the implementations still need registration of objects that is the thing that I want to come around.
As of FakeItEasy 2.1.0 (but do consider upgrading to the latest release for more features and better bugfixes), you can create a fake from a Type like so:
using FakeItEasy.Sdk;
…
object fake = Create.Fake(type);
If you must use an earlier release, you could use some reflection based approach to create a method info for the A.Fake() method. (since it's about auto mocking this shouldn't be a problem really).
This is best done using a registration handler. You should look into how AutofacContrib.Moq implements its MoqRegistrationHandler. You'll see that it is actually using the generic method MockRepository.Create to make fake instances. Creating a similar handler for FakeItEasy should be quite simple.

Linq-to-entities: How to create objects (new Xyz() vs CreateXyz())?

What is the best way of adding a new object in the entity framework. The designer adds all these create methods, but to me it makes more sense to call new on an object. The generated CreateCustomer method e.g. could be called like this:
Customer c = context.CreateCustomer(System.Guid.NewGuid(), "Name"));
context.AddToCustomer(c);
where to me it would make more sense to do:
Customer c = new Customer {
Id = System.Guid.NewGuid(),
Name = "Name"
};
context.AddToCustomer(c);
The latter is much more explicit since the properties that are being set at construction are named. I assume that the designer adds the create methods on purpose. Why should I use those?
As Andrew says (up-voted), it's quite acceptable to use regular constructors. As for why the "Create" methods exist, I believe the intention is to make explicit which properties are required. If you use such methods, you can be assured that you have not forgotten to set any property which will throw an exception when you SaveChanges. However, the code generator for the Entity Framework doesn't quite get this right; it includes server-generated auto increment properties, as well. These are technically "required", but you don't need to specify them.
You can absolutely use the second, more natural way. I'm not even sure of why the first way exists at all.
I guess it has to do with many things. It looks like factory method to me, therefore allowing one point of extension. 2ndly having all this in your constructor is not really best practice, especially when doing a lot of stuff at initialisation. Yes, your question seems reasonable, i even agree with it, however, in terms of object design, it is more practical as they did it.
Regards,
Marius C. (c_marius#msn.com)