How do you write unit tests for your java servlets? - java

what are the best practices to unit test java servlets? By the way: this is a topic in which I have some dificulty: how do you unit test your java servlets?

The most important thing to do is to try and extract everything from the servlets that isn't directly related to servlet behaviour.
This immediately makes testing core functionality a lot easier. By doing this you immediately have a set of components not tied to the container and testable without the pain of running and interfacing to a container (besides making them more reusable). Some thought should be given to architecture and the appropriate layering of components - e.g. components returning object structures rather than displayable fragments, not making use of HttpRequests directly but some request marshalling structure etc.
The majority of your tests (dependent on your system structure and complexity) can be tested normally. Additional servlet-focused tests can be built using (say) Apache Cactus to sanity check functionality. Beyond that you may wish to investigate in-browser solutions such as Selenium.
(Note: This approach works for most GUI environments - e.g. Swing)

Almost the same question was asked just today here.
Jakarta cactus is a unit-testing framework for servlets.

What we normally do is load the servlet with a mock request and response. If you're using Spring, this is especially easy since it actually provides a MockHttpRequest and MockHttpResponse.
Assuming you have clearly defined layers in your application, the rest is easy. The underlying service / DAO layer can be replaced with mocks, so we just make sure the servlet is doing what its supposed to be doing for the given request object, and writing the response correctly.

Related

Testing a java jersey application

I have a java/jersey api that is called from the front end. I need to write tests for the java code. How the code is written is:
1. The api call executes the resource method, this calls a separate method that gets data from db and returns to the resource method. This then returns a javax.ws.rs.core.Response to the client.
This is going to be my first time writing tests, so please answer considering I know nothing. What is the best way to start here? And what types of tests should I write. Unit tests are what I’m aiming for here.
Now I have done a lot of research here and I’m leaning towards using JUnit + Mockito to do this. But how do I check for the data in a Response object?
And how should I check the other file that is getting data from db? I found out DBUnit that can do that, but do I need it?
Another framework I came across was Rest Assured. Do I need to include that also? Or can the same things be done with JUnit/Mockito?
I just want some direction from people who have tested out jersey api’s. And want to know what is the most common way to do this.
I do not think there is a best way to do this, what you need to test is often subjective and dependent on the context.
However, you can structure your code in a way that the most important is tested easily and what's left (integration) can be done later / with different tools.
What I suggest here is to follow the principles of the hexagonal architecture. The idea is to keep at the center of your application and without any kind of dependencies (imports ...) to any framework (jaxrs, jpa, etc.) all business rules. These rules can be easily designed with TDD. You will then have very short running tests. It may be necessary to use Mockito to mock implementations of SPI interfaces.
In a second time, you can use this "core" by wiring adapters to the outer world (HTTP, databases, AMQP, etc.), using API and implementing SPI interfaces.
If you want to test these adapters, you exit the scope of unit-tests, and write integration-tests. Integration with a framework, a protocol, anything really.
This kind of tests can use a wide variety of tools, from a framework-related mock (like Jersey test framework), in-memory database (like H2), to fully operational middleware instance using tools like testcontainers.
What is important to remember when writing integration-tests is they are slow in regards of unit-tests. In order to keep a feedback-loop as short as possible, you will want to limit the number of integration-tests to a minimum.
Hoping this will help you!

Java Servlet: structuring a legacy webapp. What framework or technology?

I'm developing a Web app (unfortunately a legacy one) in java (that runs on tomcat) with a very small, but not well organized (at least on this particular project), group and let me start by saying we have not much of experience in servlets programming.
The issue is the folloing.
I'm having kind of a trouble as the amount of servlets keep growing and growing while we implement new functions in this webapp. We don't have a project to follow and structure. Just the clint who randomly asks for new functionality out of the blue.
I would just say our web.xml is a mess. I think we should avoid to pollute the web.xml so much with new servlet every time (right now is about 800 lines and it's becoming hard to maintain), but i'm not sure about what i should do about it.
I'm exploring different possibilities, but we can't afford to explore too much so i would like to hear some idea or best practies from people with more experience than us.
I was thinking that maybe we should use CORBA ore something like that to implenet some kind of RPC. So while grouping common functionalities in a few bunch of servlets we could tame the chaos. Could it be a good idea?
What i have in mind is something like a few servlets that pose as entry points for the requests. I would like to group them by the type of response they give. So for example i have a servlet that serves me json after calling some other class that actually do the job to extract data ore manipulating data. Or again i would have a servlet that serves me files, files that another class or servlet produce. And so on. Am i looking at the problem in the right way?
I took a looked at some framework like DWR (Direct Web Remoting) but we would need to integrate it with a legacy webapp with ugly jsp pages full of scriptlet and we can't afford to jump into full ajax web pages in the limited time we have for the project.
We would need something more lightweight.
The more i search for a solution the more i get confused and overwelmed by the possibilities i find (REST, ORB, RPC, JSON-RPC...), so i ask for your help. Thanks in advance for every answers and tips.
You should definitely look into the Spring framework which is the de-facto standard for Java web development nowadays: http://projects.spring.io/spring-framework/
The Play Framework is also an interesting framework, giving you a Ruby-like development cycle: https://www.playframework.com/
Hello many of your points are valid so you can use new frameworks like spring or struts but it needs huge change over as many new levels will get added/introduced.But if you want to just get ride of many servlets you can/should use MVC architecture like framework in addition to that use a central level controller(a main servlet)-this will just take the request and checks in it (like switch case) as soon as switch case matched that helper class / utility class should called via instance or statically after that the response should also from that helper/utility class and should be sent to the main controller and that main controller will send it to respective jsps/html.

What are pros and cons of using Spring in Swing based frontend

we have a frontend application that that uses Swing. We use Spring framework, but currently it is used just to autowire few beans...
What are reasonable next steps to use Spring more often?
Is it worth for non web application?
What would be advantages and disadvantages?
The advantages of using Spring (or any other dependency-injection) framework, is that you get a (hopefully) loosely coupled system, i.e you classes does not create instances of their collaborators, so you can easily change the implementation.
This is widely known as the Inversion-of-control principle (IoC, also the I in SOLID), and this is a good principle to follow. This means that spring is not limited to web applications, but can be used in any application that want to use an IoC-container (which is basically what spring-core is).
Disadvantages:
This really depends on how you look at things. There is more code (you have to define a entry-point for the injected collaborators), but that also makes the code more testable (the entry-points are seams which you can use to inject mocks and stubs in testing).
Also, you can't look at the code and immediately see which implementation of the collaborators that are used. But that also makes for good code, since you depend on interfaces, not implementations.
You get more config: either in an xml-file (old-style spring), or with annotations. Up until recently you had to rely on non-standard spring annotations to inject (#Autowired) resources, but now you can use the standard java dependency injection annotations, which means that you can switch out spring as your IoC-container without changing your code.
There are probably alot more advantages and disadvantages to using spring in your application, but this should get you started on deciding if using Dependency Inversion is a good thing for your application
More to the point of your question about Swing and Spring. In an application I have been working on we have been using spring to wire up the whole application. The different dialogs get their logic injected (no application logic should (in my opinion) be located together with gui logic). We are using JPA/hibernate as the database-layer, so we use spring spring to create and inject the entitymanager to our DAOs, and set up transactional settings.
I've written swing UI's that are backed by spring.
cons
the startup can be slower but you have to have a large app for that to happen.
and a splashscreen is a good idea in those situations.
its easy to "overbean" or over-zealously make everything a bean, which gets messy.
pros
spring works fine behind a GUI.
it provides a lot of services you can use
the obvious dependency injection and decoupling
a global event system, simpifying some of your own event listeners, for events that will only ever be fired by one source
resource accessing
database access is eays in 2 tier apps
rpc for 3 tier apps is easy
There are other services the spring application context provides, but that I haven't used.
If you go this direction, also look into the java-based configuration for spring, which is new in 3.0. I find that helpful as well, as it makes my spring configuration type-safe.
One disadvantage of using Spring in a Swing application is that Spring DI will make startup slower.
well one would be , if you ever decide to migrate to a web app , all you need ( well almost) to change would be the views. That's the beauty of MVC applications.

Custom web MVC for a legacy Java EE project

I am in the middle of creating my own custom MVC web framework for a project. This project has very old code base where one JSP page directly submits a form to another JSP whereas the paths are also hardcoded. Now it is a big project and putting Struts or JSF will take considerable amount of time.
So my suggestion is to build a small custom MVC framework and convert many existing page flows into it and also encourage them to develop newer applications using this new MVC frameworks.
I would like to review this with all of you whether it makes sense or we should directly go to the standard MVC frameworks.
My idea
1. Create one front controller servlet which will have URL pattern like /*.sm
2. This servlet reads one config file and creates a map whose key is requestedURI and value is the class name of the command bean.
3. upon intercepting any action request it reads the parameter map (request.getParameterMap()). This servlet refers the already built map, understand whose command bean is to be invoked? Creates an instance of this command bean.
4. pass the parameter map to this command bean and calls execute method.
5. if any exception is found, front controller servlet forwards the request to one global error page
6. if everything is fine, it then forwards the request to the expected URI (by removong .sm and replace it with .jsp)
Do you think I am missing anything here? I know I can make it more fancy by providing error page per request page in the config file or so but those can be done later as well.
I think that you will end up reinventing the wheel rolling your own MVC framework. I know that it is tempting to make your own, since you won't have to get used to a new API but instead create your own and you can more easily adapt it to your specific usecases. But since it seems to be a very long lived application you will have to consider the fact, that your own framework (which may now be state of the art) will be legacy in a couple of years, too.
And that's where adapting one of the popular frameworks comes in handy. The creators of a new framework usually want others to move, too, so they will (or should) offer easy integration or migration options away from the frameworks they think they are doing better (Spring is a good example since it e.g. seamlessly integrates with existing Struts applications and you can gradually move your application without putting the old one into trash). Additionally most current frameworks are very versatile (which can sometimes be a problem since they need more time to get into it) and can be adapted to almost all usecases.
So I would recommend to review the existing solutions carefully (you can learn a lot from their design decisions and errors, too) and only start making your own if none of them matches your requirements.

Simpler-than-JBoss way to have POJO RPC in Java with container session management

Currently, I only know a way of doing RPC for POJOs in Java, and is with the very complex EJB/JBoss solution.
Is there any better way of providing a similar functionality with a thiner layer (within or without a Java EE container), using RMI or something that can serialize and send full blown objects over the wire?
I'm not currently interested in HTTP/JSON serialization BTW.
EDIT: For clarification: I'm trying to replace an old EJB 2.1/JBoss 4 solution with something more easy to manage at the container level. I need to have entire control over the database(planning to use iBATIS which would allow me to use fairly complex SQL very easily), but the only things I want to keep over the wire are:
Invocation of lookup/data modification methods (automagic serialization goes here).
Transparent session control (authentication/authorization). I still have to see how to accomplish this.
Both items have to work as a whole, of course. No access should be granted to users without credentials.
Because I'm not very fond of writing webapps, I plan to build a GUI (Swing or SWT) that would only manage POJOs, do some reporting and invoke methods from the container. I want the serialization to be as easy as possible.
As is nearly always the case, Spring comes to the rescue. From the reference documentation, you will want to read Chapter 17. Remoting and web services using Spring.
There are several methods to choose from. The beauty of Spring is that all your interfaces and implementations are vanilla POJOs. The wiring into RMI or whatever is handled by Spring. You can:
Export services using RMI:
probably the simplest approach;
Use HTTP invoker: if remote access is an issue, this might be better for firewalls, etc than pure RMI; or
Use Web Services, in which case I would favour JAX-WS over JAX-RPC.
Spring has the additional benefit in that it can do the wiring for both the server and the client, easily and transparently.
Personally I would choose either (2) or (3). HTTP is network friendly. It's easy to deploy in a Web container. Jetty's long-lived connections give you the option over server push (effectively) over HTTP.
All of these methods allow complex objects to be sent across the wire but they are subtly different in this regard. You need to consider if your server and client are going to be distributed separately and whether it's an issue if you change the interface that you need to redistribute the class files. Or you can use a customized serialization solution (even XML) to avoid this. But that has issues as well.
Using a Web container will allow you to easily plug-in Spring Security, which can be a bit daunting at first just because there are so many options. Also, HttpSession can be used to provide state information between requests.
Simple RPC is exactly what RMI was built for. If you make a serializable interface, you can call methods on one app from another app.
If you only need value objects then just ensure the POJOs implement Serializable and write the objects across sockets (using ObjectOutputStream). On the receiving end read the objects using ObjectInputStream. The receiving end has to have a compatible version of the POJO (see serialVersionUID).
Hessian/Burlap 'protocol-ize this: http://hessian.caucho.com/ and http://www.caucho.com/resin-3.0/protocols/burlap.xtp
You could try XStream (http://x-stream.github.io/) over REST. Easy to apply on e pre-existing set of pojos.
Can you give some further information as to what you're trying to achieve, since you're not interested in rest/json ?

Categories

Resources