Weblogic 10 embeddable EJB container - junit

My task is to come with automated integration tests for a legacy EJB 2.1 code base that is running on Weblogic 10.1 server. Does anybody know if there is an emeddable container I can use in JUnit? I can see plenty of examples for Weblogic 12 , but not 10.
Any relevant suggestion will be highly appreciated.

You can try with mockejb. It is working fine for my testcases.
Just giving some sample.
<dependency>
<groupId>mockejb</groupId>
<artifactId>mockejb</artifactId>
<scope>test</scope>
</dependency>
private ServiceAccess bean;
private ServiceAccessHome home;
protected void setUp() throws Exception {
super.setUp();
MockServiceAccessBean mockServiceAccessbean = new MockServiceAccessBean();
MockContextFactory.setAsInitial();
MockContainer container = new MockContainer(new InitialContext());
container.deploy(new SessionBeanDescriptor("ServiceAccess", ServiceAccessHome.class,
ServiceAccess.class, mockServiceAccessbean));
home = (ServiceAccessHome) new InitialContext().lookup("ServiceAccess");
bean = home.create();
}
public void tearDown() throws Exception {
MockContextFactory.revertSetAsInitial();
bean.remove();
super.tearDown();
}

Related

JUnit 5 vintage not running tests in nested static classes

I have JUnit 4 tests I am trying to run with JUnit 5 Vintage.
I have many tests in nested static classes. Tests in top level classes run fine, but tests in the nested classes don't run.
For example:
public class SomeOuterClass {
#Test
public void outerTest() {
// test runs
}
public static class SomeInnerTests {
#Test
public void someTest() {
// test doesn't run
}
}
public static class OtherInnerTests {
#Test
public void otherTest() {
// test doesn't run
}
}
}
I tried setting junitPlatform.filters.includeClassNamePatterns to '^.*Tests?$', '^.*Tests?\$.*$' but it didn't work.
You can execute JUnit 4 with JUnit 5 using JUnit 5 Vintage,
Use it by importing the JUnit Vintage Engine:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit5.vintage.version}</version>
<scope>test</scope>
</dependency>
JUnit 5 Vintage added support for running nested static classes in the final release.
By default it only finds classes whose names end in "Test(s)". To include nested static classes that aren't named like that, set the following in your build file.
junitPlatform.filters.includeClassNamePatterns '^.*Tests?$', '^.*Tests?\\$.*$'

Spring AOP - #Pointcut: #Before advice for #Test methods does not work

I am working with:
Spring Framework 4.3.2
AspectJ 1.8.9
JUnit
Gradle
The project is based in multi-modules.
In src/main/java (main) I have some #Aspect classes and they work how is expected. I can confirm it through Runtime and Testing
Now I need for JUnit through logging show the #Test method name that is executed
Therefore in src/test/java (test) I have the following:
class TestPointcut {
#Pointcut("execution(#org.junit.Test * *())")
public void testPointcut(){}
}
#Aspect
#Component
public class TestAspect {
private static final Logger logger = LoggerFactory.getLogger(TestAspect.class.getSimpleName());
#Before(value="TestPointcut.testPointcut()")
public void beforeAdviceTest(JoinPoint joinPoint){
logger.info("beforeAdviceTest - Test: {} - #Test: {}", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName() );
}
}
Observe the second class has #Aspect and #Component therefore it is recognized by Spring
Note: I can confirm that If I write wrong the #Pointcut syntax or expression I get errors.
The problem is when I execute my #Test methods, For the TestAspect class the #Before advice never works.
I did a research in Google and I have seen that the #Pointcut("execution(#org.junit.Test * *())") pattern is correct.
Even If I use a more explicit such as: #Pointcut(value="execution(public void com.manuel.jordan.controller.persona.*Test.*Test())"), it does not work.
Consider I have the following for Gradle
project(':web-27-rest') {
description 'Web - Rest'
dependencies {
compile project(':web-27-service-api')
testRuntime project(':web-27-aop')
testRuntime project(':web-27-aop').sourceSets.test.output
What is missing or wrong?
Alpha:
One kind of Test classes are:
Server side working with #Parameters and #ClassRule + #Rule
Therefore:
#RunWith(Parameterized.class)
#ContextConfiguration(classes={RootApplicationContext.class})
#Transactional
public class PersonaServiceImplTest {
#ClassRule
public static final SpringClassRule SPRING_CLASS_RULE= new SpringClassRule();
#Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
#Autowired
private PersonaService personaServiceImpl;
...
#Parameters
public static Collection<Persona[]> data() {
.....
});
}
...
#Test
#Sql(scripts={"classpath:....-script.sql"})
public void saveOneTest(){
....
}
Other are:
Web side working with (#WebAppConfiguration) and either:
with #Parameters and #ClassRule + #Rule
without #Parameters and #ClassRule + #Rule
Therefore (below the second approach):
#Transactional
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={RootApplicationContext.class, ServletApplicationContext.class})
public class PersonaDeleteOneControllerTest {
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
private ResultActions resultActions;
...
#BeforeClass
public static void setUp_(){
...
}
#Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void deleteOneHtmlGetTest() throws Exception {
JUnit instantiates your test class. Thus, Spring is not involved and therefore cannot apply AOP advice to the test instance.
As was mentioned by Sergey Bespalov, the only way to have AspectJ advice applied to your test instance is to use compile-time or load-time weaving. Note that this would not be configured within Spring. Spring can be used to configure AOP for Spring-managed beans, but the test instance is managed by the testing framework (i.e., JUnit 4 in your scenario).
For tests using the Spring TestContext Framework, however, I would not recommend using AspectJ. Instead, the best solution is to implement a custom TestExecutionListener that performs the logging. You could then register that TestExecutionListener explicitly via #TestExecutionListeners or have it picked up automatically for your entire suite. For the latter, see the discussion on automatic discovery in the Testing chapter of the Spring reference manual.
Regards,
Sam (author of the Spring TestContext Framework)
You can use AspectJ Compile or Load time weaving as alternative of spring-aop proxying. In such approach you will not depend on spring context complicated logic to apply advices in your code. Aspect code will be just inlined during compilation or class loading phase.
Example below shows how to enable AspectJ Compile Time Weaving:
pom.xml
This Maven configuration enables AspectJ compiler that makes bytecode post processing of your classes.
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
</dependencies>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.6</version>
<configuration>
<showWeaveInfo>true</showWeaveInfo>
<source>${java.source}</source>
<target>${java.target}</target>
<complianceLevel>${java.target}</complianceLevel>
<encoding>UTF-8</encoding>
<verbose>false</verbose>
<XnoInline>false</XnoInline>
</configuration>
<executions>
<execution>
<id>aspectj-compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>aspectj-compile-test</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
applicationContext.xml
Also you may need to add aspect instance to Spring Application Context for dependency injection.
<bean class="TestAspect" factory-method="aspectOf"/>

PowerMockito and Mockito conflict

I need to built unit tests (with junit) for a legacy system. The method that I need to test, makes use of a static method and I need to check if it's called. So, I'll need to use PowerMockito (for "regular" mocking, we use mockito).
But, when I include PowerMockito statements inside the test, Mockito fails with an org.mockito.exceptions.misusing.UnfinishedStubbingException. If I comment the lines PowerMockito.mockStatic(Application.class), PowerMockito.doNothing().when(Application.class) and PowerMockito.verifyStatic(), the UnfinishedStubbingExceptiondoes does not occur, but this way, I'm not able to check if my IllegalArgumentException occured.
The method under test looks like:
public class ClientMB {
public void loadClient(Client client) {
try {
if (client == null) {
throw new IllegalArgumentException("Client is mandatory!");
}
setClient(clientService.findById(client.getId()));
} catch (Exception ex) {
Application.handleException(ex);
}
}
}
And the test looks like:
#PrepareForTest({ Application.class })
#RunWith(PowerMockRunner.class)
public class ClientMBTest {
#Test
public final void testLoadClient() {
ClientService mockedClientService = Mockito.mock(ClientService.class);
Mockito.when(mockedClientService.findById(42L)).thenReturn(new Client());
PowerMockito.mockStatic(Application.class);
PowerMockito.doNothing().when(Application.class);
ClientMB cmb = new ClientMB(mockedClientService);
mb.loadClient(null);
PowerMockito.verifyStatic();
}
}
I imported PowerMokito using the latest version.
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
What I'm doing wrong? Any advice is welcome.
PowerMockito.doNothing().when(Application.class);
That's a stubbing command, but because you don't make a method call after the when(...), it's unfinished.
PowerMockito.doNothing().when(Application.class);
Application.someApplicationMethod();
You need to use this syntax because the normal doVerb().when(foo) syntax will provide an instance, and Java often issues a warning when trying to call a static method based on an instance instead of a class name.
If you want to stub all of Application's methods, you can do so by passing another argument into mockStatic:
PowerMockito.mockStatic(Application.class, RETURNS_SMART_NULLS);

How to handle RPCs in client-server PlayN game?

I'd like to use PlayN to create a client/server card game, e.g. Hearts. While I'm mostly focusing on the HTML5 output, I'd ideally like to be output-platform-agnostic in case I decide to make an Android client in the future. How should I approach the RPC mechanism?
These are the options I've thought of:
Use JSON for RPCs with get()/post() methods - write a servlet that accepts/returns JSON, and make all versions of client code use that. This seems doable, but I'm concerned about JSON's verbosity. Once I get Hearts working I'd like to move on to more complex games, and I'm worried that JSON will result in a lot of much-larger-than-necessary messages being passed back and forth between client and server. I don't actually know how to work with JSON in Java, but I assume this is doable. Are my assumptions in-line? How well does Java work with JSON?
Continue using GWT-RPC. I can do this by taking an asynchronous service interface in my core (platform-agnostic) constructor, and in my HTML main() I pass in the GWT Async interface generated by GWT.create(MyService.class) (or at least a wrapper around it). I have no idea how well this would work for non-HTML versions though. Is it possible for me to use GWT-RPC from client-side Java code directly?
Use some other form of RPC. Any suggestions?
For the GWT RPC on the Java and Android platforms, I'm currently experimenting with using gwt-syncproxy to provide Java client access to the GWT RPC methods, and I'm using Guice, Gin, and RoboGuice on their respective target platforms to inject the appropriate asynchronous service instances for the instantiated Game object.
In the core/pom.xml for a PlayN project, I include the following dependency coordinates to support DI from Gin/Guice/RoboGuice as needed:
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
Then I add #Inject annotations to any fields inside of the concrete Game implementation:
public class TestGame implements Game {
#Inject
TestServiceAsync _testService;
...
}
In the html/pom.xml, I include the dependency coordinates for Gin:
<dependency>
<groupId>com.google.gwt.inject</groupId>
<artifactId>gin</artifactId>
<version>1.5.0</version>
</dependency>
And I create TestGameGinjector and TestGameModule classes:
TestGameGinjector.java
#GinModules(TestGameModule.class)
public interface TestGameGinjector extends Ginjector {
TestGame getGame();
}
TestGameModule.java
public class TestGameModule extends AbstractGinModule {
#Override
protected void configure() {
}
}
Since at the moment, I'm only injecting the TestServiceAsync interface, I don't need to put any implementation in the TestGameModule.configure() method; Gin manages instantiation of AsyncServices for me via GWT.create().
I then added the following to TestGame.gwt.xml
<inherits name='com.google.gwt.inject.Inject'/>
And finally, I made the following changes to TestGameHtml.java
public class TestGameHtml extends HtmlGame {
private final TestGameGinjector _injector = GWT.create(TestGameGinjector.class);
#Override
public void start() {
HtmlPlatform platform = HtmlPlatform.register();
platform.assetManager().setPathPrefix("test/");
PlayN.run(_injector.getGame());
}
}
And this pretty much covers the HTML5 platform for PlayN.
For the Java platform, I add the following dependency coordinates to java/pom.xml:
<dependency>
<groupId>com.gdevelop.gwt.syncrpc</groupId>
<artifactId>gwt-syncproxy</artifactId>
<version>0.4-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0-rc2</version>
</dependency>
Do note that the gwt-syncproxy project on Google Code does not contain a pom.xml. I have a mavenized version of gwt-syncproxy forked and available via git at https://bitbucket.org/hatboyzero/gwt-syncproxy.git. You should be able to clone it, run mvn clean package install to get it into your local Maven repository.
Anyways, I created a TestGameModule.java for the Java platform as follows:
public class TestGameModule extends AbstractModule {
#Override
protected void configure() {
bind(TestServiceAsync.class).toProvider(TestServiceProvider.class);
}
public static class TestServiceProvider implements Provider<TestServiceAsync> {
public TestServiceAsync get() {
return (TestServiceAsync) SyncProxy.newProxyInstance(
TestServiceAsync.class,
Deployment.gwtWebPath(), // URL to webapp -- http://127.0.0.1:8888/testgame
"test"
);
}
}
}
And I modified TestGameJava.java as follows:
public class TestGameJava {
public static void main(String[] args) {
Injector _injector = Guice.createInjector(new TestGameModule());
JavaPlatform platform = JavaPlatform.register();
platform.assetManager().setPathPrefix("test/images");
PlayN.run(_injector.getInstance(TestGame.class));
}
}
I went through a similar exercise with the Android platform and RoboGuice -- without going into tremendous detail, the relevant changes/snippets are as follows:
pom.xml dependencies
<dependency>
<groupId>com.gdevelop.gwt.syncrpc</groupId>
<artifactId>gwt-syncproxy</artifactId>
<version>0.4-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.roboguice</groupId>
<artifactId>roboguice</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0-rc2</version>
<classifier>no_aop</classifier>
</dependency>
TestGameApplication.java
public class TestGameApplication extends RoboApplication {
#Override
protected void addApplicationModules(List<Module> modules) {
modules.add(new TestGameModule());
}
}
TestGameModule.java
public class TestGameModule extends AbstractModule {
#Override
protected void configure() {
bind(TestServiceAsync.class).toProvider(TestServiceProvider.class);
}
public static class TestServiceProvider implements Provider<TestServiceAsync> {
public TestServiceAsync get() {
return (TestServiceAsync) SyncProxy.newProxyInstance(
TestServiceAsync.class,
Deployment.gwtWebPath(), // URL to webapp -- http://127.0.0.1:8888/testgame
"test"
);
}
}
}
TestGameActivity.java
public class TestGameActivity extends GameActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
final Injector injector = ((RoboApplication) getApplication()).getInjector();
injector.injectMembers(this);
super.onCreate(savedInstanceState);
}
#Override
public void main(){
platform().assetManager().setPathPrefix("test/images");
final Injector injector = ((RoboApplication) getApplication()).getInjector();
PlayN.run(injector.getInstance(TestGame.class));
}
}
That's a quick and dirty rundown of how I got Gin/Guice/RoboGuice + GWT working in my project, and I have verified that it works on both Java and HTML platforms beautifully.
Anyways, there's the GWT approach to providing RPC calls to multiple PlayN platforms :).

Getting started with rhino service bus

I've read a lot of examples/tutorials (incl. Ayende's Alexandria on MSDN).
But just getting somewhat updated assemblies have proven to be an obstacle in itself. After getting the correct version of Castle.Windsor - it cannot find the correct section in the app.config file. The syntax in both Rhino Service Bus and the CastleBootstrapper has been changed as well - and I'm now totally confused. The 'documentation' on Hibernating Rhinos is really not helping me get started.
Could anyone please help me a working sample with Rhino Service Bus with either Castle Windsor v. 3.0 (beta) or 2.5.3, point me at something already online or just giving me a step-by-step pointers on what I need to get up and running?
after downloading the latest Rhino-ESB bits from github (https://github.com/hibernating-rhinos/rhino-esb) and building it, it's pretty straightforward to get started.
I have a asp.net MVC application which communicates with a backend through Rhino-ESB.
On the asp.net MVC side:
On global.asax.cs:
private IWindsorContainer _container;
protected void Application_Start()
{
_container = new WindsorContainer();
new RhinoServiceBusConfiguration().UseCastleWindsor(_container).Configure();
_container.Install(new YourCustomInstaller());
//Don't forget to start the bus
_container.Resolve<IStartableServiceBus>().Start();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container));
}
Note that YourCustomInstaller must implement IWindsorInstaller and you register your controllers with the container in the Installmethod:
public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
{
container.Register(Component
.For<HomeController>().LifeStyle.PerWebRequest.ImplementedBy<HomeController>());
Also note that the WindsorControllerFactory internally delegates controller creation to the container:
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
return (IController)this.container.Resolve(controllerType);
}
Last but not least, provide the configuration on your web.config
<configSections>
<section name="rhino.esb" type="Rhino.ServiceBus.Config.BusConfigurationSection, Rhino.ServiceBus"/>
</configSections>
<rhino.esb>
<bus threadCount="1"
numberOfRetries="5"
endpoint="rhino.queues://localhost:31316/Client"
queueIsolationLevel="ReadCommitted"
name="Client"/>
<messages>
<add name="YourMessagesNamespace"endpoint="rhino.queues://localhost:31315/Backend"/>
</messages>
</rhino.esb>
This configuration assumes that the backend runs a queue in localhost:31315 and the client runs its queue on localhost:31316.
On the backend side:
assuming we're running it as a console application,
static void Main(string[] args)
{
IWindsorContainer container;
container = new WindsorContainer();
new RhinoServiceBusConfiguration()
.UseCastleWindsor(container)
.Configure();
var host = new RemoteAppDomainHost(typeof(YourBootstrapper));
host.Start();
Console.WriteLine("Starting to process messages");
Console.ReadLine();
Notice that YourBootstrapperclass implements CastleBootstrapper
public class YourBootstrapper: Rhino.ServiceBus.Castle.CastleBootStrapper
{
protected override void ConfigureContainer()
{
Container.Register(Component.For<OneOfYourMessages>());
}
}
in which we're registering a consumer for OneOfYourMessages