Spring & Mockito - ignore transitive dependencies - unit-testing

I have a layered application that looks like this:
#PreAuthorize('isAuthenticated()')
#Controller
public class MyController {
#Autowired
MyService service;
}
#Service
public class MyService {
#Autowired
MyDao dao;
}
public interface MyDao {
}
#Repository
public class MyDaoImpl implements MyDao {
}
I want to test the AOP-dependent #PreAuthorize annotation, so I use the SpringJUnit4ClassRunner which creates a test AuthenticationManager and MyController.
If the #ContextConfiguration does not include any bean matching MyService, test initialization fails because it can't resolve the bean.
If I didn't need AOP, I would use Mockito test runner and inject Mockito.mock(MyService.class). But if I try and do it with spring runner, again my test fails because it can't resolve MyDao for the service (even though the service a mock).
I definitely don't want to mock the whole object graph. I'd rather it stopped on the mocked service. How can I do it?

Your MyService should implement an interface, and you should mock the interface instead of the class. Then you won't need a DAO implementation. You might also, perhaps, be running into a similar issue that I faced while trying to test a JAX-RS resource class in Jersey. The problem is how to deploy a single bean into a Spring container but mock its dependencies. I wrote a blog post on it that might help you out if this is the problem you're facing. In particular, the final solution may be of help.

Related

MissingMethodInvocationException while using when() method on a service which InjectMocks

I am writing unit tests for my service PlanGenerator. I have mocked necessary services and I have InjectMocked plangenerator service as follows:
#Mock
private LoggerFactory lf;
#Mock
private Logger logger;
#Mock
private RequestGenerator requestGenerator;
#InjectMocks
private PlanGenerator planGenerator;
In methods, I am able to call when method on Mocked services like requestGenerator as this:
Mockito.when(requestGenerator.getLatestRequest()).thenReturn(latestRequestDummy);
However, I am not able to call the same method on planGenerator service like this:
Mockito.when(planGenerator.someOtherMethod()).thenReturn(someValue);
It gives me MissingMethodInvocationException error while saying when() requires an argument which has to be 'a method call on a mock'
How can I mock planGenerator service, also it works as same as injectmocks?

RESTful application without web.xml

I have created a sample project and used EJB 3.1 with a RESTful web service. In the sample I have a class which extends Application. I expect the class works like a servlet and dispatch requests to appropriate classes but it does not. When I use web.xml my sample project works fine. What is wrong with my sample project?
#ApplicationPath("/rest")
public class ApplicationServlet extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(UserWS.class);
return classes;
}
}
I use UserWS as a EJB session bean which exposes web service:
#Stateless
#LocalBean
#Path("/user")
public class UserWS {
private int count;
public UserWS() {
this.count=0;
}
#GET
#Path("/name/{username}")
public void getUserName(#PathParam("username") String username) {
count++;
System.out.println("count is:"+ count);
}
}
I'm afraid it won't be possible once JBoss 5.0 supports only Servlet 2.5. For more details, see here.
To avoid the web.xml deployment descriptor, you need a servlet container the supports at least Servlet 3.0.
So, what could you do to solve it?
These are the options that came up to my mind:
You could try upgrading the JBoss Web (Tomcat fork used by JBoss AS) as described here, but try that at you own risk.
Consider using a recent version of JBoss/WildFly.

JBoss WebServices and EJB

My application should show a list of stuff over RESTful WebServices.
This list of stuff is generated via an EJB which is deployed in JBoss AS 6 in a .jar.
My question is, how do I get this list of stuff in order to show it via Web Services?
If I try to inject #EJB in the stateless bean annotated with #WebService, and try to invoke the method that generates the list, I get an error saying that #EJB cannot be resolved (or imported). (fixed it, needed to modify maven dependencies).
Now I get a NullPointerException when I call the supposedly injected EJB...
I am using the webapp archetype from Maven, which contains an EAR, a JAR and a WAR.
I am at a total loss here, been trying to figure this for almost a week.
Thanks in advance!
--EDIT-- code and typo fixed
This is my stateless bean which SHOULD be exposed as a WebService (according to:
http://www.adam-bien.com/roller/abien/entry/restful_calculator_with_javascript_and )
#Stateless
#Path("/MyRESTApplication")
public class HelloWorldResource {
#EJB
private TestBean testBean;
#GET()
#Produces("text/plain")
public String sayHello(String name) {
return testBean.doMoreStuff();
}
}
the doMoreStuff() function simply returns "HELLO!".

CDI Constructor Injection in a JAX-WS web service

I have a JAX-WS webservice deployed to a Java EE 6 container.
I would like to use CDI to inject session beans to this webservice. Up till now I have successfully been doing this using field injection but the company policy is to use constructor based injection. The webservice implementation is NOT a session bean. So is
#WebService
public class MyWebservice{
private ServiceA serviceA;
private ServiceB serviceB;
#Inject
public MyWebservice( ServiceA serviceA, ServiceB serviceB)
{
this.serviceA = serviceA;
this.serviceB = serviceB;
}
public void webMethod1()
{
serviceA.doSomething();
serviceB.doSomething();
}
}
acceptable to CDI?

Singleton class with #Startup annotation WL 11g

i have a problem deploying my webservice to Weblogic 11g.
JAVA: JRockit 1.6.x
I need to run a method on webservice deployment and i made this code:
#Singleton
#Startup
public class StartupBean {
Logger logger = Logger.getLogger(StartupBean.class);
#PostConstruct
private void postConstruct() {
logger.error("WS started.");
}
#PreDestroy
private void preDestroy() {
logger.error("WS stoped.");
}
}
without any additional xml config.
It works normally on 12c but i need it on 11g.
What is the workaround?
Thanks
No, you can't do this in pre-3.1-EJB without XML config.
The common practice in EJB 3.0 for implementing a #Startup bean was to instantiate in in a servlet, which is configured to load on startup in web.xml. If you need it just for log4j you can initialize it directly from such servlet.