Programmatically create a Mockito SpyBean of a given Class - spring

My abstract test needs to create a SpyBean of a defined class within the concrete implementation and I do not want the implementation or the "user" to have to add the #SpyBean annotation.
How can I programmatically create a SpyBean of a given Class without using the #SpyBean annotation?

Related

#Autowired works in an abstract class

Hy,
How #Autowired works in an attribute declared in an abstract class if its not inherited in the subclasses. What spring does under the hood in order the subclasses have the dependency injected in them if #Autowired annotation is not inherited in the subclasses?
Thanks
There's no such thing as a not inherited field in subclasses in Java. The private fields get inherited just as any other non-static field, they're just not visible in the subclass code. They can still be accessed with reflection though. Spring will have no problem autowiring such fields.

Does Spring #transaction work on a concrete method of abstract class

From spring reference doc
Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the #Transactional annotation, as opposed to annotating interfaces. You certainly can place the #Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java
annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.
Though it only talks about interfaces, abstract classes are considered as non-concrete as well.
So if i have an abstract class
public abstract class BaseService{
//here is a concrete method
#Transactional
public void updateData{
//do stuff using dao layer
}
and a concrete class which extends the class
public class SpecialService extends BaseService{
//body of class
}
Now if i call specialService.updateData() from my controller class will it be transactional?
Granting that you have actually configured Spring transaction management correctly, using #Transactional on an abstract superclass will work, since #Transactional is itself annotated with #Inherited and from it's Javadoc we have:
Indicates that an annotation type is automatically inherited. If an
Inherited meta-annotation is present on an annotation type
declaration, and the user queries the annotation type on a class
declaration, and the class declaration has no annotation for this
type, then the class's superclass will automatically be queried for
the annotation type. This process will be repeated until an annotation
for this type is found, or the top of the class hierarchy (Object) is
reached. If no superclass has an annotation for this type, then the
query will indicate that the class in question has no such annotation.
Note that this meta-annotation type has no effect if the annotated
type is used to annotate anything other than a class. Note also that
this meta-annotation only causes annotations to be inherited from
superclasses; annotations on implemented interfaces have no effect.
To actually see that #Transactional is annotated with #Inherited check out it's Javadoc

How does Mockito #InjectMocks work?

Here's my question:
I have several web services classes to test that all inherit their methods from a generic service. Rather than write a unit test for each, I figure I can break the test suite down by functional areas (i.e. three groups of test methods, each relying on a different underlying DAO method call).
What I propose to do is:
#Mock StateDAO mockedStateDao;
#Mock CountyDAO mockedCountyDao;
#Mock VisitorDAO mockedVisitorDao;
then call:
#InjectMocks CountyServiceImpl<County> countyService = new CountyServiceImpl<County>();
#InjectMocks StateServiceImpl<State> stateService = new StateServiceImpl<State>();
#InjectMocks VisitorServiceImpl<Visitor> visitorService = new VisitorServiceImpl<Visitor>();
How can I be sure that each mockedDAO will be injected into the correct service?
Would it be easier to autowire all three (rather than use #InjectMocks)?
I'm using Spring, Hibernate, and Mockito...
Well nicholas answer is almost correct, but instead of guessing just look at the javadoc of InjectMocks, it contains more details ;)
To me it's weird to have so many Service in a single test, it doesn't feel right, as a unit test or as an integration test. In unit test it's wrong because well you have way too much collaborators, it doesn't look like object oriented (or SOLID). In integration tests, it's weird because the code you test the integration with the DB not mock it.
For a rapid reference in 1.9.5 you have :
Mark a field on which injection should be performed.
Allows shorthand mock and spy injection.
Minimizes repetitive mock and spy injection.
Mockito will try to inject mocks only either by constructor injection, setter injection, or property injection in order and as described below. If any of the following strategy fail, then Mockito won't report failure; i.e. you will have to provide dependencies yourself.
Constructor injection; the biggest constructor is chosen, then arguments are resolved with mocks declared in the test only.
Note: If arguments can not be found, then null is passed. If non-mockable types are wanted, then constructor injection won't happen. In these cases, you will have to satisfy dependencies yourself.
Property setter injection; mocks will first be resolved by type, then, if there is several property of the same type, by the match of the property name and the mock name.
Note 1: If you have properties with the same type (or same erasure), it's better to name all #Mock annotated fields with the matching properties, otherwise Mockito might get confused and injection won't happen.
Note 2: If #InjectMocks instance wasn't initialized before and have a no-arg constructor, then it will be initialized with this constructor.
Field injection; mocks will first be resolved by type, then, if there is several property of the same type, by the match of the field name and the mock name.
Note 1: If you have fields with the same type (or same erasure), it's better to name all #Mock annotated fields with the matching fields, otherwise Mockito might get confused and injection won't happen.
Note 2: If #InjectMocks instance wasn't initialized before and have a no-arg constructor, then it will be initialized with this constructor.
If you have multiple Services and would like to replace the DAOs with Mock-Objects in a Spring-based environment, I would recommend to use Springockito: https://bitbucket.org/kubek2k/springockito/wiki/Home
which is also mentioned here:
Injecting Mockito mocks into a Spring bean
Your Testclass then might look like this:
#RunWith (SpringJUnit4ClassRunner.class)
#ContextConfiguration (loader = SpringockitoContextLoader.class, locations = {"classpath:/org/example/package/applicationContext.xml"})
public class NameOfClassTest {
#Autowired
#ReplaceWithMock
StateDAO mockedStateDao;
#Autowired
#ReplaceWithMock
CountyDAO mockedCountyDao;
#Autowired
#ReplaceWithMock
VisitorDAO mockedVisitorDao;
In your #Test or #Before Methode you can setup your mocks the standard Mockito way:
Mockito.doReturn(null).when(mockedCountyDao).selectFromDB();
Well, the static method MockitoAnnotations.initMocks(Object) is used to bootstrap the whole process.
I don't know for sure how it works, as I haven't browsed the source code, but I would implement it something like this:
Scan the passed Object's class for member variables with the #Mock annotation.
For each one, create a mock of that class, and set it to that member.
Scan the passed Object's class for member variables with the #InjectMocks annotation.
Scan the class of each found member for members it has that can be injected with one of the mock objects created in (2) (that is, where the field is a parent class/interface, or the same class, as the mock objects declared class) and set it to that member.
Nevermind, looked online- the InjectMocks annotation treats anything with the #Mock annotation as a field and is static-scoped (class wide), so I really couldn't guarentee that the mocks would go to the correct service. this was somewhat a thought experiment for trying to unit test at feature level rather than class level. Guess I'll just autowire this stuff with Spring...

how to implement Factory Pattern with Spring 3.0 Services

In my project I have an interface annotated with org.springframework.stereotype.Service tag.
I have two different implementation for this interface.
In my manage bean, I am injecting interface Service class and using its methods.
Now my requirement is, in run time I have to pick particular implementation (lets say based on login user group) so that respective logic can be invoked.
As per my understanding, we can achieve this using Factory pattern in java and achieve the same.
How can we implement this in SPRIng???
Besides suggested related topic above, there is a good thread on JavaRanch.
You can use
#Qualifier("myServiceImpl1") annotation together with #Autowired. In
that case this particular implementation of the interface will be
injected. You should also use the same name with your #Component,
#Service or #Repository annotations e.g.
#Service("myServiceImpl1")
public class MyServiceImpl1 implements MyService{}
public class Consumer{
#Autowired
#Qualifier("myServiceImpl1")
public MyService myServiceImpl1;
}
#Primary together with #Component, #Service or #Repository
annotations in your implementation class, in that case this
implementation will be injected by default.
If you mark a list of some interface type with #Autowired, all
available implementations of this interface will be injected.
#Autowired
public List<MyService> allAvailableImplementations;

Is it OK to define RowMapper class as spring bean?

On many tutorial/books about spring JDBC, RowMapper class usually represented as private static final class inside DAO and the instance is created in every single query.
Does RowMapper have to be used and instantiate in this way?
Is it ok if I define RowMapper class as spring bean using #Component annotation and #Autowired it to my dao class?
Which one is better?
Does RowMapper have to be used and instantiate in this way
No, that's just a common usage pattern.
Is it ok if I define RowMapper class as spring bean using #Component annotation and #Autowired it to my dao class?
Sure, that would work. Unless the RowMapper needs access to other Spring services, though, there's not much point.
Which one is better?
Without seeing your code and getting a feel for your application, we can't really tell you if it's a good idea or not, only you can make that choice.
My personal preference would be to keep the RowMapper as a non-static inner class of your DAO class, and to insantiate it directly from the DAO. If the RowMapper needs access to other Spring beans, then wire those intop the DAO, and access them from the RowMapper inner class.

Resources