Inject CDI bean in a Junit test script - junit

I have an application running on JBoss AS 7.1.1. This app uses some resources of CDI specification as interceptors, injection, etc. The architecture of my app is very simple with the structure below:
view (xhtml and facelets)
controller (managed beans with #Named, except in the ViewScoped)
model (divided in two layers, service and dao)
service (with #Stateless annotation, here I use an interceptor that I created to manage the transactions with database, because I use native JDBC)
dao
I need to create some scripts to test the application service layer, injecting the service implementation and invoking the business methods.
I believe that this architecture is very common. I'm sorry for my english.
Can someone help me, please?
Thanks!

If you want to test your full container, you probably want Arquillian. If you want to do Unit testing with mocks, start a standalone weld container in your test using weld-se.
new Weld().initialize().instance().select(YourClassName.class).get();
You can substitute your mock objects by using alternatives in your beans.xml. You can also use CDI-Unit which simplifies the process a bit.

Related

.Net Core 1.0.0, multiple projects, and IConfiguration

TL;DR version:
What's the best way to use the .Net Core IConfiguration framework so values in a single appsettings.json file can be used in multiple projects within the solution? Additionally, I need to be able to access the values without using constructor injection (explanation below).
Long version:
To simply things, lets say we have a solution with 3 projects:
Data: responsible for setting up the ApplicationDbContext, generates migrations
Services: class library with some business logic
WebApi: REST API with a Startup.cs
With this architecture, we have to use a work-around for the "add-migration" issue that remains in Core 1.0.0. Part of this work-around means that we have a ApplicationDbContextFactory class that must have a parameterless constructor (no DI) in order for the migration CLI to use it.
Problem: Right now we have connection strings living in two places;
ApplicationDbContextFactory for the migration work-around
in the WebApi's "appsettings.json" file
Prior to .Net Core, we could use ConfigurationManager to pull connection strings for all solution projects from one web.config file based on the startup project. How do we use this new IConfiguration framework to store connection strings in one place that need to be used all over the solution? Additionally, I can't inject into the ApplicationDbContextFactory class' constructor... so that further complicates things (more-so since they changed how the [FromServices] attribute works).
Side note: I would like to avoid implementing an entire DI middleware just to get attribute injection, since Core includes it's own DI framework. If I can avoid that and still access appsettings.json values, that would be ideal.
If I need to add code let me know, this post was already long enough, so I'll hold off on examples until requested. ;)

Should EasyMock be used to mock only external services?

I have a question concerning the use of EasyMock in junits. We have configured a framework for junits which uses inmemory derby database and EasyMock to test our service project. We use in memory derby for dao layer completely. The question arises on weather to use EasyMock completely or easymock and derby together in the service layer. Below is the scenario :
//class under test is in user-service project
class ServiceClassUnderTest {
IUserService userService;
IAddressService addressService;
public Address getUsersAddress(String id) {
User user = userService.getUserById(id);
// some logic goes here
Address address = addressService.getAddresdByUser(user);
// some validations goes here
return address;
}
}
The class under test is in user-service project and so is the IUserService interface. While IAddressService interface is in address-service project used as a dependency in user-service project.
Now the problem is in the change of approach suggested by some colleagues.
Approach we used to follow
Prepare test data for userService as its in the same project and mock addressService as its part of a dependency project and we might not have much idea about its behaviour and table structure
Advantage : cleaner approach as we have mimimal code for mocking and test data is in separate sql files
Suggested approach
Mock all services irrespective of its being in the same project or part of a dependency project
Disadvantage : more mocking relevant code then actual test related code, making it difficult to maintain and compromises readability.
The code example given is to only explain the scenario where as in real project we have a lot more complex structure with several service beans in a single class.
Could you please give me your suggestions on which approach is better and why considering the arguments provided by me for both approaches ??
A definitive is hard without have the complete big picture. Assuming you really want unit tests, I usually do this:
Test only the query done to the DB with an actual DB
Mock everything that is used by my tested class.
This "everything" should be no more than 3 or 4 dependencies. Otherwise, I will refactor until I get something that is readable.
Having more test code than production code is normal.
If I end up having trivial code in my tested method, I just don't test it. However, a test can also be used to document. So this is a blurry line.

Configuration profiles in EJB 3+

With Spring there is the concept of Profile annotations...
which are great when one wants to build up components for development/test apart from production setups. How do people handle this in EJB 3+?
Seen in http://www.amazon.com/Real-World-Java-Patterns-Rethinking-Practices/dp/1300149310 that CDI injection can be used (i.e. Logger Injection). Basically one creates a Configuration class that produces settings that are injected into other classes that produce (#Alternative classes) based of these settings. Not as smooth as Spring profiles but would work.
Any other ways in EJB/CDI?

What makes up the "standard jmock libraries"?

I'm following this guide http://javaeenotes.blogspot.com/2011/06/short-introduction-to-jmock.html
I've received the error
java.lang.SecurityException: class "org.hamcrest.TypeSafeMatcher"'s signer information does not match signer information of other classes in the same package.
In the guide the author says:
The solution is make sure the jMock libraries are included before the
standard jUnit libraries in the build path.
What makes up the "standard jmock libraries" and the "junit libraries"?
Junit only has one jar so that's easy, but jmock comes with over 10 different jars.
I've been using: j-unit4.10, jmock-2.5, hamrest-core and hamcrest-library
What are the hamcrest core and library classes for?
i'm a committer on both libraries. JMock depends on hamcrest to help it decide whether an call to an object is expected. I suggest just using the hamcrest-all jar. The split between hamcrest core and library was to separate the fundamental behaviour of matching and reporting differences from a convenient implementations of the most common cases.
Finally, if you're using hamcrest, I suggest you use the junit-dep jar to avoid clashes with some features of hamcrest that are included in the junit.jar
JUnit is used to do Unit test in order to test your methods. JMock is used to test your program inside a context, You will have to know what you are expecting to send to the context (ENV) and what will answer the context.
JMock use JUnit, that is why, in order to avoid dependency conflicts, you need to include it before JUnit.
The 10 libraries of JMock are kind of add-ons if you need to use JMock script or any other functionnality not available in the JMock core.
You don't need to know about Hamcrest-core library to use JMock. Just follows the guide on the web site (don't use version 1 of JMock) and Organize your libraries in the correct order (JUnit should be last in order to avoid your error)
mock frameworks licke jmock do some black magic behind the scenes
( including, but not limited to runtime byte code manipulation )
to provide mock methods classes and whatever. To be able to do this,
some tweaks in basic junit classes are necessary, and the only way to do this is to
register itself as java agent before JU classes are loaded.
Also, put your mock framework before junit in classpath

Unit testing with a Singleton

I am developing an AS3 application which uses a Singleton class to store Metrics in Arrays. It's a Singleton because I only ever want one instance of this class to be created and it needs to be created from any part of the app.
The difficulty comes when I want to unit test this class. I thought adding public getters and setters would enable me to unit test this properly and would be useful for my app. I have read that changing to a Factory pattern will enable unit testing or using Inversion of control. This would of course make it more flexible too. I would like to know of people's thoughts on this matter as there are SO many conflicting opinions on this!
Thanks
Chris
If you're using an IoC framework, then make your consumers require an instance of the service in their constructor, and configure the IoC framework to only build one instance and keep handing it out to all requests in the entire application. This is the default behavior of Castle Windsor in my experience.
For unit testing you can use a Mock object in place of the real object.