Is there a way to unit test a HttpEvent based servlet? - unit-testing

I have a Comet Servlet which has been coded using Jboss Advanced IO techniques, trhough the usage of HttpEventServlet interface.
Are there any frameworks that can be used to unit test such a code? So far, I have tried jUnit and HttpUnit with no sucess. My google search didn't return any positive results for this question as well.
I would like to invoke the event method in my unit tests
/**
* Process the given event.
*
*/
public void event(HttpEvent event) { ... }

Related

What test to write?

I know this is a basic question but due to lack of my knowledge I couldn't start writing test for my application. So here I am trying to learn and understand what to test and how to test based on my application scenario.
Class MyController {
MyService service = new MyService();
List<String> myList = service.generateSomeList(keyVal);
model.add("myList", myList);
}
Class MyService {
ThirdPatryService extService = new ThirdPatryService ();
MyDao dao = new MyDao();
public List<String> generateSomeList(Long key) {
List<String> resultList = dao.fetchMyList(key);
extService.processData(resultList); //using 3rd party service to process result. It doesn't return anything.
return formattedList(resultList);
}
private List<String> formattedList(List<String> listToProcess) {
//do some formatting
}
}
Class MyDao {
List<String> fetchMyList(key) {
//Use DB connection to run sql and return result
}
}
I want to do both unit testing and integration testing. So some of my questions are:
Do I have to do unit testing for MyDao? I don't think so since I can test query result by testing service level.
What can be the possible test cases for service level? I can think of test result from db and test formatting function. Any other test that I missed?
While testing generateSomeList() method is that OK to create dummy String list and test it against result? Like code below Am I creating list myself and testing myself. IS this proper/correct way to write test?
#Test
public void generateSomeListTest() {
//Step 1: Create dummy string list e.g. dummyList =["test1", "test2", "test3"]
//Step 2: when(mydao.fetchMyList(anyLong()).thenReturn(dummyList);
//Step 4: result=service.generateSomelist(123L);
//Step 5: assertEquals(result[i], dummyList[i]);
}
I don't think I have to test third party service but I think I have to make sure it is being called. Is this correct? If yes how can I do that with Mockito?
How to make sure thirdparty service has really done the processing of my data. Since its return type is void how can I do test it really done its job e.g like send email
Do I have to write test for controller or I can just write integration test.
I really appreciate if you could answer these question to understand the testing part for the application.
Thanks.
They're not really unit tests, but yes, you should test your DAOs. One of the main points in using DAOs is precisely that they're relatively easy to test (you store some test data in the database, then call a DAO method which executes a query, and check that the method returns what it should return), and that they make the service layer easy to test by mocking the DAOs. You should definitely not use the real DAOs when testing the services. Ue mock DAOs. That willmake the service tests much simpler, and much much faster.
Testing the results from DB is the job of the DAO test. The service test should use a mock DAO that returns hard-coded results, and checks that the service foes what it should do with these hard-coded results (formatting, in this case)
Yes, it's fine.
Usually, it's sufficient to stub the dependencies. Verifying that they have been called is often redundant. In that case, it could be a good idea since the third party service doesn't return anything. But that's a code smell. Why doesn't it return something? See the method verify() in Mockito. It's the very first point in the Mockito documentation: http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#1
The third party service is supposed to have been tested separately and thus be reliable. So you're supposed to assume that it does what its documentation says it does. The test for A which uses B is not supposed to test B. Only A. The test of B tests B.
A unit test is usually simpler to write and faster to execute. It's also easier to test corner cases with unit tests. Integration tests should be more coarse-grained.
Just a note: what your code severely lacks as is is dependency injection. That's what will make your code testable. It's very hard to test as is because the controller creates its service, which creates its DAO. Instead, the controller should be injected with the service, and the service should be injected with the DAO. That's what allows injecting a mock DAO in the service to test the service in isolation, and to inject a mock service into the controller to test the controller in isolation.

Unit testing for Jfreecharts

I am constructing a simple linechart using JFreechart API.. Can anyone let me know how to unit test it using mockito. I am still kind of new to do unit testing framework. Dont really know how it works
public LineChart(String applicationTitle, String chartTitle) {
super(applicationTitle);
// Create the dataset
CategoryDataset dataset = new DataSet().createDataLineSet();
JFreeChart chart = createChart(dataset, chartTitle);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(CHART_WIDTH,
CHART_HEIGHT));
setContentPane(chartPanel);
}
/**
* Creates a sample chart
*
* #param dataset
* ,the chartTitle
*
* #return The chart.
*/
public JFreeChart createChart(CategoryDataset dataset, String chartTitle) {
// TODO Auto-generated method stub
// create the chart
JFreeChart chart = ChartFactory.createLineChart(chartTitle, // chart
// title
categoryAxisLabel, // category axis label
valueAxisLabel, // value axis label
dataset, // data
PlotOrientation.VERTICAL, // chart orientation
true, // include legend?
true, // include tooltips?
false // URLs?
);
return chart;
}
The way you've structured it, this is a particularly hard class to unit test, and I'm not sure how much value unit testing would provide. Is this code for a school or work project with a "unit test all your code" directive?
First, a clarification based on your tags: Mockito is not a unit testing framework.
junit is a unit testing framework that allows you to write classes with methods that exercise classes. Using exceptions, as well as calls to Assert.assertEquals, Assert.assertTrue, and Assert.fail (for instance) you can write tests with minimal boilerplate. Reading JUnit's Getting Started page may help.
mockito is a mocking framework, which allows you create mocks and stubs of objects and verify that you're system under test is interacting with its collaborators correctly. Though it's preferable to unit test just by checking the return value of a method call or the state of the system after your test, certain classes require interaction with external systems. The first few numbered items of the Mockito documentation may help.
At least three things make your class hard to test using mocks and JUnit:
Your system under test is directly calling constructors. This gives you very little opportunity to substitute in simpler implementations or mocks for test.
The collaborator you're interacting with (JFreeChart API) is designed for GUIs. It can be hard to test GUI-oriented classes in a headless, reproducible way, which are two typical aspects of unit tests.
The collaborator is third-party software, which can be dangerous to mock. Mocking relies on some implementation details (like whether methods are public or final) that can be dangerous for code that's not directly under your control.
Remember also that it is an anti-pattern to test the implementation—unit tests are designed to check that your code produces the correct results. Looking at the code that you posted, I'm not sure what I would test there.
On the other hand, if you have a separate part of the project that loads and processes numeric data to feed into your chart, it would be very straightforward and useful to produce a JUnit test that takes in data from a sample file, runs it through the loader/processor you write, and ensures that it produces the correct numbers that you've worked out and confirmed by hand. The continued passing of that test is some guarantee that your code still works as expected, even if the implementation of your loader/processor were to change.

How to test GWT/GWTP project?

I am currently building a web application using GWT, GWTP.
And I have some questions about testings:
Is there a Lint-like tool for GWTP or GWT?
How to test presenters? (GWTP with Mockito)
How to test views?
Thanks.
Presenters can be easily unit-tested using Jukito. Here's a quick example of a Presenter being tested using Jukito.
#RunWith(JukitoRunner.class)
public class ShowCommentsPresenterTest {
#Inject
private ShowCommentsPresenter showCommentsPresenter;
#Inject
private PlaceManager placeManager;
#Test
public void onReset_PlaceRequestHasNoShowId_ShouldHideView() {
//given
when(placeManager.getCurrentPlaceRequest()).thenReturn(new PlaceRequest());
//when
showCommentsPresenter.onReset();
//then
verify(showCommentsPresenter.getView()).hide();
}
#Test
public void onReset_PlaceRequestHasAShowId_ShouldDisplayView() {
//given
String someShowId = "12345";
when(placeManager.getCurrentPlaceRequest()).thenReturn(new PlaceRequest()
.with(ParameterTokens.getShowId(), someShowId));
//when
showCommentsPresenter.onReset();
//then
verify(showCommentsPresenter.getView()).display();
}
}
In GWTP's philosophy, Views should not be unit-tested directly. Using a dumb View that is a slave to the Presenter, most of the logic can be tested through unit tests on the Presenters. Tools like Selenium are a better fit for testing UI interactivity.
Google put out a great article about using different testing methodologies with GWT. Definitely check it out. Personally, I use JUnit when I'm testing back-end stuff like business logic, and Selenium for testing the UI and application as a whole from the browser's perspective.

Unit Testing.... a data provider?

Given problem:
I like unit tests.
I develop connectivity software to external systems that pretty much and often use a C++ library
The return of this systems is nonndeterministic. Data is received while running, but making sure it is all correctly interpreted is hard.
How can I test this properly?
I can run a unit test that does a connect. Sadly, it will then process a life data stream. I can say I run the test for 30 or 60 seconds before disconnecting, but getting code ccoverage is impossible - I simply dont even comeclose to get all code paths EVERY ONCE PER DAY (error code paths are rarely run).
I also can not really assert every result. Depending on the time of the day we talk of 20.000 data callbacks per second - all of which are not relly determined good enough to validate each of them for consistency.
Mocking? Well, that would leave me testing an empty shell of myself because the code handling the events basically is the to be tested case, and in many cases we talk here of a COMPLEX c level structure - hard to have mocking frameworks that integrate from Csharp to C++
Anyone any idea? I am short on giving up using unit tests for this part of the application.
Unit testing is good, but it shouldn't be your only weapon against bugs. Look into the difference between unit tests and integration tests: it sounds to me like the latter is your best choice.
Also, automated tests (unit tests and integration tests) are only useful if your system's behavior isn't going to change. If you're breaking backward compatibility with every release, the automated tests of that functionality won't help you.
You may also want to see a previous discussion on how much unit testing is too much.
Does your external data source implement an interface -- or can you using a combination of an interface and a wrapper around the data source that implements the interface decouple your class under test from the data source. If either of these are true, then you can mock out the data source in your unit tests and provide the data from the mock instance.
public interface IDataSource
{
public List<DataObject> All();
...
}
public class DataWrapper : IDataSource
{
public DataWrapper( RealDataSource source )
{
this.Source = source;
}
public RealDataSource Source { get; set; }
public List<DataObject> All()
{
return this.Source.All();
}
}
Now in your class under test depend on the interface and inject an instance, then in your unit tests, provide a mock instance that implements the interface.
public void DataSourceAllTest()
{
var dataSource = MockRepository.GenerateMock<IDataSource>();
dataSource.Expect( s => s.All() ).Return( ... mock data ... );
var target = new ClassUnderTest( dataSource );
var actual = target.Foo();
// assert something about actual
dataSource.VerifyAllExpectations();
}

Can I unit test a method that makes Sitecore context calls?

I'm working on a web application that is built over Sitecore CMS. I was wondering if we could unit test for example a method that takes some data from Sitecore makes some processing with it and spits out a result. I would like to test all the logic within the method via a unit test.
I pretty confused after searching the internet wide and deep. Some say that this kind of testing is actually integration testing and not unit testing and I should test only the code that has no Sitecore calls, others say that this is not possible because the Sitecore context would be missing.
I would like to ask for your help experienced fellow programmers:
Can I unit test a method that contains Sitecore calls ? If YES, how ? If NO, why ? Is there any workaround ?
The project is at its beginning, so there will be no problem in choosing between unit testing frameworks such as MSTest or Nunit, if it is the case that the solution is related to the unit testing framework of choice.
It's pretty hard to find out anything about Sitecore without providing email and living through the sales pitch, so I'll just provide a generic approach on how to do something like this.
First and foremost, you assume that the Sitecore API is guaranteed to work - i.e. it's a framework - and you don't unit test it. You should be unit testing your interactions with it.
Then, download MOQ and read the quick start on how to use it. This is my preferred mocking framework. Feel free to use other frameworks if you wish.
Hopefully, Sitecore API provides a way for you to create data objects without dealing with persistence - i.e. to simply create a new instance of whatever it is you are interested in. Here is my imaginary API:
public class Post {
public string Body {get;set;}
public DateTime LastModified {get;set;}
public string Title {get;set;}
}
public interface ISiteCorePosts {
public IEnumerable<Post> GetPostsByUser(int userId);
}
In this case unit testing should be fairly easy. With a bit of Dependency Injection, you can inject the SiteCore interfaces into your component and then unit test it.
public class MyPostProcessor {
private readonly ISiteCorePosts m_postRepository;
public MyPostProcessor(ISiteCorePosts postRepository) {
m_postRepository = postRepository;
}
public void ProcessPosts(int userId) {
var posts = m_postRepository.GetPostsByUser(userId);
//do something with posts
}
}
public class MyPostProcessorTest {
[TestMethod]
ProcessPostsShouldCallGetPostsByUser() {
var siteCorePostsMock = new Mock<ISiteCorePosts>();
//Sets up the mock to return a list of posts when called with userId = 5
siteCorePostsMock.Setup(m=>m.GetPostsByUser(5)).Returns(new List<Post>{/*fake posts*/});
MyPostProcessor target = new MyPostProcessor(siteCorePostsMock.Object);
target.ProcessPosts(5);
//Verifies that all setups are called
siteCorePostsMock.VerifyAll();
}
}
If ISiteCorePosts is not, in fact, an interface and is a concrete class whose methods are not virtual and thus cannot be mocked, you will need to use Facade pattern to wrap the SiteCore interaction to make it more testing friendly.
public class SiteCorePostsFacade {
SiteCorePosts m_Posts = new SiteCorePosts();
//important - make this method virtual so it can be mocked without needing an interface
public virtual IEnumerable<Post> GetPostsByUser(int userId) {
return m_Posts.GetPostsByUser(userId);
}
}
You then proceed to use SiteCorePostsFacade as though it was an interface in the previous example. Good thing about MOQ is that it allows you to mock concrete classes with virtual methods, not just interfaces.
With this approach, you should be able to inject all sorts of data into your application to test all interactions with SiteCore API.
we have used a custom WebControl placed on a WebForm for our integration tests some years now, which wraps the NUnit Test Suite runner functionality much like the NUnit GUI. It show a pretty grid of executed tests with links to fixtures and categories to execute specific tests. Its created much like described here http://adeneys.wordpress.com/2010/04/13/new-technique-for-unit-testing-renderings-in-sitecore/ (the custom test runner part). Our implementation can also return raw NUnit xml for further processing by for example a build server.
I've tried MSTest a while back and it also works when specified that it should launch a WebDev / IIS site to test. It works but is extremely slow compared to above solution.
Happy testing!
Short answer:
You need to mock calls to SiteCore CMS.
Long answer:
I am not aware about SiteCore CMS. But, from your question looks like it is something that is external to your application. Components external to your system should always be used via interface. This has two benefits:
If you want to use another CMS system, you can easily do as your application is just talking to an interface.
It helps you with behavior testing by mocking the interface.
The code you write is your responsibility and hence you should only unit test that piece of code. Your unit tests should ensure that your code calls appropriate SiteCode CMS methods in various scenarios (behavior tests). You can do this using mocking. I use moq for mocking.
As tugga said, it depends upon how tightly the code you want to test is coupled to SiteCore. If it's something like:
SomeSiteCoreService siteCoreDependency = new SomeSiteCoreService()
Then this would be very difficult to test. If SiteCore provides you an interface, then you have more flexibility to unit test it. You could pass the implementation into your method either (contstructor, class property, or method parameter) and then you can send in a fake implementation of that service.
If they do not provide you with an interface, then you have to do a little more work. You would write an adapter interface of your own and the default implementation would delegate to the 3rd party dependency.
public interface ICMSAdapter{
void DoSomethingWithCMS()
}
public class SiteCoreCMSAdapter: ICMSAdapter{
SiteCoreService _cms = new SiteCoreService();
public void DoSomethingWithCMS(){
_cms.DoSomething();
}
That keeps your 3rd party dependencies at arms length and provides seams to all sorts of cool things, like unit tests and you do interception style architecture and do your own thing before and after the call.
}
I was able to get unit tests to interact with sitecore api in VS 2015. The same test throws a StackOverflow exception when run in VS 2012.
For example, this method call runs fine in VS2015 but not VS2015:
Context.SetActiveSite("mysite");
quick note: this assumes you have a site named mysite setup in your config file