Write junit for a final class using #postconstruct using mockito - java

I am trying to write a junit using mockito api for a final class and using #PostConstruct annotaion. Below is the sample code which I have written so far.
public final class ConfigCache {
private static final MultiKeyMap configCache = new MultiKeyMap();
#Autowired
private ConfigDao dao;
#PostConstruct
public void init() {
Map<String, Collection<Configuration>> map = null;
try {
if (configurationCache != null || configurationCache.isEmpty()) {
map = dao.loadConfigurations();
map.forEach((k, v) -> {
v.forEach((c) -> {
configCache.put(k, c.getAttributeName(), c.getAttributeValue());
});
});
}
} catch (DaoException e) {
throw new RuntimeException(e);
}
}
public Object getValue(String k1, String k2) {
return configurationCache.get(k1, k2);
}
#PreDestroy
public void clearCache() {
if (configCache != null) {
configCache.clear();
}
}
}
Junit which I have so far is
#RunWith(SpringRunner.class)
#SpringBootTest(classes = {ConfigCache.class})
public class ConfigCacheTest {
#InjectMocks
private ConfigCache configCache;
#MockBean
private ConfigDao dao;
private Map<String,Collection<Configuration>> map;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#After
public void tearDown() {
}
#Test
public void testInit() throws DaoException {
map = new HashMap<String,Collection<Configuration>>();
List<Configuration> configurations = new ArrayList<Configuration>();
Configuration configuration = new Configuration();
configuration.setAttributeName("a");
configuration.setAttributeValue("20");
configurations.add(configuration);
configuration = new Configuration();
configuration.setAttributeName("b");
configuration.setAttributeValue("10");
configurations.add(configuration);
map.put("abc", configurations);
when(dao.loadConfigurations()).thenReturn(map);
assertEquals("ConfigurationCacheBuilder.init()",configurationCacheBuilder.getConfigurationcache().size(),1);
}
}
When I run this, I get an error
java.lang.ExceptionInInitializerError
at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.<init>(ConditionalStackTraceFilter.java:17)
at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:41)
at org.mockito.exceptions.base.MockitoException.<init>(MockitoException.java:30)
at org.mockito.exceptions.misusing.MockitoConfigurationException.<init>(MockitoConfigurationException.java:18)
at org.mockito.internal.configuration.plugins.PluginLoader.loadImpl(PluginLoader.java:66)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:24)
at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:12)
at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:11)
at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:24)
at org.springframework.boot.test.mock.mockito.MockReset.<clinit>(MockReset.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.lang.Class.getEnumConstantsShared(Class.java:3320)
at java.lang.Class.enumConstantDirectory(Class.java:3341)
at java.lang.Enum.valueOf(Enum.java:232)
at sun.reflect.annotation.AnnotationParser.parseEnumValue(AnnotationParser.java:483)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:347)
at java.lang.reflect.Method.getDefaultValue(Method.java:606)
at sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:128)
at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:85)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:266)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.reflect.Field.declaredAnnotations(Field.java:1150)
at java.lang.reflect.Field.declaredAnnotations(Field.java:1148)
at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:1139)
at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:207)
at org.junit.runners.model.FrameworkField.getAnnotations(FrameworkField.java:31)
at org.junit.runners.model.TestClass.addToAnnotationLists(TestClass.java:84)
at org.junit.runners.model.TestClass.scanAnnotatedMembers(TestClass.java:71)
at org.junit.runners.model.TestClass.<init>(TestClass.java:57)
at org.junit.runners.ParentRunner.createTestClass(ParentRunner.java:88)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:83)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:138)
at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NullPointerException
at org.mockito.internal.configuration.plugins.Plugins.getStackTraceCleanerProvider(Plugins.java:17)
at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.<clinit>(StackTraceFilter.java:21)
... 55 more
I tried with 2 versions of mockito
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
</dependency>
and
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.5.5</version>
can someone let me know what might be going wrong ?

One way you can solve this is by creating a package level setter for dao variable.
void setConfigDao(ConfigDao configDao) {
dao = configDao;
}
And then, avoid to use #InjectMocks in class ConfigCacheTest and initialize your configCache object in setUp() method.
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
configCache = new ConfigCache();
configCache.setConfigDao(dao);
configCache.init();
}
This way, you can avoid this NPE when #PostConstruct init() method is called before mockito injects dao object.

Related

Mockito running in java 8 but giving unfinished stubbing error in java 11

I am using mockito to mock some methods while writing unit tests. It is working fine in java 8, but when i use java 11 it gives these errors :
java.lang.IllegalStateException: message == null
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
This is the mockito dependency i am using :
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
This is the sample unit test :
public class ClientTest {
private OtherClient otherClient;
#Mock
private OkHttpClient client;
#Mock
private Call call;
#Before
public void setUp() throws IOException {
MockitoAnnotations.initMocks(this);
otherClient = new OtherClient(client, new ObjectMapper(), "http://localhost:8080");
Mockito.when(client.newCall(Mockito.any())).thenReturn(call);
}
#Test
public void testUploadSuccess() throws IOException {
Response.Builder builder = new Response.Builder();
builder.code(200);
builder.request(new Request.Builder().url("http://localhost:8080").build());
builder.protocol(Protocol.HTTP_1_1);
builder.body(ResponseBody.create(MediaType.parse("application/json"), "{}"));
Mockito.when(call.execute()).thenReturn(builder.build());
File temp = File.createTempFile("upload", "test.pdf");
try {
otherClient.upload("test", temp,
FileUploadRequest.builder().build(),
ImmutableMap.of("Authorization", ""));
} catch (UploadException e) {
Assert.fail("Failed to Upload");
} finally {
FileUtils.deleteQuietly(temp);
}
}
}
Please help.

Could not find class [de.flapdoodle.embed.process.config.IRuntimeConfig]

After upgrading to embeded MongoDB with version 3.0.0, I am getting the following exception.
I am using the following in build.gradle.
testImplementation group: 'de.flapdoodle.embed', name: 'de.flapdoodle.embed.mongo', version: '3.0.0'
The exception is given below.
Caused by: java.lang.ClassNotFoundException: de.flapdoodle.embed.process.config.IRuntimeConfig
at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_261]
at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_261]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) ~[na:1.8.0_261]
at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_261]
at java.lang.Class.forName0(Native Method) ~[na:1.8.0_261]
at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_261]
at org.springframework.util.ClassUtils.forName(ClassUtils.java:284) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:324) ~[spring-core-5.2.10.RELEASE.jar:5.2.10.RELEASE]
I provide below the code. I want to use embeded mongoDB for the MongoDB transaction feature in the integration test in spring boot.
#Profile("test")
#ActiveProfiles("test")
public class TestMongoConfig1 implements InitializingBean, DisposableBean {
MongodForTestsFactory factory = null;
MongodConfig mongodConfig = MongodConfig.builder().version(Version.Main.PRODUCTION).build();
MongodStarter runtime = MongodStarter.getDefaultInstance();
MongodExecutable mongodExecutable = null;
MongodProcess mongod = null;
#Override
public void destroy() throws Exception {
mongodExecutable.stop();
}
#Override
public void afterPropertiesSet() throws Exception {
mongodExecutable = runtime.prepare(mongodConfig);
mongod = mongodExecutable.start();
}
#Bean(name = "test1")
public MongoClient mongoClient() {
MongoClient mongoClient = MongoClients.create();
System.out.println("============================================");
System.out.println(mongoClient);
System.out.println("============================================");
return mongoClient;
}
}
First you have to use the following dependencies in build.gradle apart from other dependencies if you are using #DataMongoTest.
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
testImplementation("de.flapdoodle.embed:de.flapdoodle.embed.mongo")
To test with embeded MongoDB, you have to use the following snippet which may work.
#Profile("test")
#ActiveProfiles("test")
#Configuration
public class TestMongoConfig1 implements InitializingBean, DisposableBean {
private MongodExecutable executable;
#Override
public void afterPropertiesSet() throws Exception {
IFeatureAwareVersion version = Versions.withFeatures(new GenericVersion("4.0.0"),
Version.Main.PRODUCTION.getFeatures());
IMongoCmdOptions cmdOptions = new
MongoCmdOptionsBuilder().useNoPrealloc(false).useSmallFiles(false)
.master(false).verbose(false).useNoJournal(false).syncDelay(0).build();
int port = Network.getFreeServerPort();
IMongodConfig mongodConfig = new MongodConfigBuilder().version(version)
.net(new Net(port, Network.localhostIsIPv6())).replication(new Storage(null, "testRepSet", 5000))
.configServer(false).cmdOptions(cmdOptions).build();
MongodStarter starter = MongodStarter.getDefaultInstance();
executable = starter.prepare(mongodConfig);
executable.start();
}

How to make SlingHttpServletRequest.getParts() return the proper value in JUnit Test?

I am facing some difficulties in writing junit test to pass the for loop condition to getParts() method from SlingHttpServletRequest.getParts(). There is no problem with the implementation, I am able to process the file attachment properly. However, I am unable to do so in the junit test.
The following is my implementation:
#Model(adaptables = SlingHttpServletRequest.class)
public class Comment {
//Variables declaration
#Inject
private CommentService service;
#PostConstruct
public void setup() {
requestData = new JSONObject();
for (String item : request.getRequestParameterMap().keySet()) {
try {
requestData.put(item, request.getParameter(item));
}
} catch (Exception e) {
Throw error message
}
}
//Upload attachment to server
try {
for (Part part : request.getParts()) { <= The JUnit test stopped at this line and throw the error below
} catch (Exception e) {
Throw error message
}
I have tried using a SlingHttpServletRequestWrapper class to override the getParts method but to no avail.
The following is my junit test:
public class CommentTest {
public final AemContext context = new AemContext();
private CommentService commentService = mock(CommentService.class);
#InjectMocks
private Comment comment;
private static String PATH = "/content/testproject/en/page/sub-page";
#Before
public void setUp() throws Exception {
context.addModelsForPackage("de.com.adsl.sightly.model");
context.load().json("/components/textrte.json", PATH);
context.currentPage(PATH);
}
#Test
public void testSetup() throws IOException, ServletException {
//before
context.request().setParameterMap(getRequestCat1());
context.registerService(CommentService.class, commentService);
Resource resource = context.resourceResolver().getResource(PATH + "/jcr:content/root/responsivegrid/textrte");
assertNotNull(resource);
//when
comment = new CustomRequest(context.request()).adaptTo(Comment.class);
//then
comment.setup();
}
private class CustomRequest extends SlingHttpServletRequestWrapper {
public CustomRequest(SlingHttpServletRequest request) {
super(request);
}
#Override
public Collection<Part> getParts() {
final String mockContent =
"------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" +
"Content-Disposition: form-data; name=\"key\"\n" +
"\n" +
"myvalue1\n" +
"------WebKitFormBoundarycTqA2AimXQHBAJbZ";
final List<Part> parts = MockPart.parseAll(mockContent);
assertNotNull(parts);
return parts;
}
};
}
The following is the error message that I encountered:
14:53:04.918 [main] ERROR de.com.adsl.sightly.model.Comment - Error Message: null
java.lang.UnsupportedOperationException: null
at org.apache.sling.servlethelpers.MockSlingHttpServletRequest.getParts(MockSlingHttpServletRequest.java:882) ~[org.apache.sling.servlet-helpers-1.1.10.jar:?]
at de.com.adsl.sightly.model.Comment.uploadFile(Feedback.java:137) ~[classes/:?]
at de.com.adsl.sightly.model.Comment.setup(Feedback.java:82) [classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_201]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_201]
at org.apache.sling.models.impl.ModelAdapterFactory.invokePostConstruct(ModelAdapterFactory.java:792) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.createObject(ModelAdapterFactory.java:607) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.internalCreateModel(ModelAdapterFactory.java:335) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.getAdapter(ModelAdapterFactory.java:211) [org.apache.sling.models.impl-1.3.8.jar:?]
...
I have looked up various solutions online such as writing two mockito when statements but has not been successful. I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!
From the source code of MockSlingServletResquest it always throws that exception as it's not supported yet by the mocked class.
https://github.com/apache/sling-org-apache-sling-servlet-helpers/blob/71ef769e5564cf78e49d6679a3270ba8706ae406/src/main/java/org/apache/sling/servlethelpers/MockSlingHttpServletRequest.java#L953
Maybe you should consider writing a servlet, or another approach.

Test Eclipse 4 RCP Application. Provide necessary Objects

I´m developing an Eclipse 4 RCP Application and I want to test some functions of my Parts.
I have a Test Class like this:
#BeforeClass
public static void initUI() {
display = new Display();
shell = new Shell(display);
configPart = new ConfigPart();
configPart.postConstruct(shell);
}
#Test
public void testConfigPart() {
String testText = "TitleText";
configPart.title.setText(testText);
assertEquals(testText, ConfigHandler.getInstance().getInternalConfig()
.getTitle());
}
During the creation of the ConfigPart a DataBinding is created and that is where I run into an AssertionFailedException. The statement is:
DataBindingContext ctx = new DataBindingContext();
Is there a way to avoid this or is there another way to test E4 Applications?
Edit:
The statement(s) where the Exception is raised:
public DataBindingContext(Realm validationRealm) {
Assert.isNotNull(validationRealm, "Validation realm cannot be null");
public static void isNotNull(Object object, String message) {
if (object == null) throw new AssertionFailedException("null argument:" + message);
The Stack Trace:
org.eclipse.core.runtime.AssertionFailedException: null argument:Validation realm cannot be null
at org.eclipse.core.runtime.Assert.isNotNull(Assert.java:85)
at org.eclipse.core.databinding.DataBindingContext.<init>(DataBindingContext.java:95)
at org.eclipse.core.databinding.DataBindingContext.<init>(DataBindingContext.java:82)
at de.uni_due.s3.jack.editor.parts.config.ConfigPart.addDataBinding(ConfigPart.java:350)
at de.uni_due.s3.jack.editor.parts.config.ConfigPart.postConstruct(ConfigPart.java:81)
at de.uni_due.s3.jack.editor.parts.config.ConfigPartTest.initUI(ConfigPartTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
A call to the empty constructor new DataBindingContext() delegates to this(Realm.getDefault()) (see Eclipse source code). This means that you need to have some kind of a stub Realm set as default for your testing purposes.
You can use this solution from the Eclipse Wiki. Here is a copy-paste from the Wiki (adapted for your setup). I would think about whether you really need to have the setup in #BeforeClass or if #Before would be better.
public class DefaultRealm extends Realm {
private Realm previousRealm;
public DefaultRealm() {
previousRealm = super.setDefault(this);
}
/**
* #return always returns true
*/
public boolean isCurrent() {
return true;
}
protected void syncExec(Runnable runnable) {
runnable.run();
}
/**
* #throws UnsupportedOperationException
*/
public void asyncExec(Runnable runnable) {
throw new UnsupportedOperationException("asyncExec is unsupported");
}
/**
* Removes the realm from being the current and sets the previous realm to the default.
*/
public void dispose() {
if (getDefault() == this) {
setDefault(previousRealm);
}
}
}
Test code:
private static DefaultRealm realm;
#BeforeClass
public static void initUI() {
display = new Display();
shell = new Shell(display);
realm = new DefaultRealm();
configPart = new ConfigPart();
configPart.postConstruct(shell);
}
#AfterClass
public static void tearDownUI() {
realm.dispose();
}

No tx on thread CMP OpenEJB4 JUnit Hibernate

I keep getting the following exception,
java.lang.IllegalStateException: No tx on thread at org.apache.geronimo.transaction.manager.TransactionManagerImpl.getActiveTransactionImpl(TransactionManagerImpl.java:201)
at org.apache.geronimo.transaction.manager.TransactionManagerImpl.getResource(TransactionManagerImpl.java:194)
at org.apache.openejb.core.transaction.JtaTransactionPolicy.getResource(JtaTransactionPolicy.java:111)
at org.apache.openejb.core.transaction.EjbTransactionUtil.afterInvoke(EjbTransactionUtil.java:76)
at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:246)
at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:178)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:260)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:240)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:91)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:284)
at $Proxy70.call(Unknown Source)
at com.xyz.cms.epgmgmt.entitymanager.ProviderManagerTest.testWithTransaction(ProviderManagerTest.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I am using OpenEJB4 for JUnit testing.
The EJB itself is stateless with no transaction annotation (which makes the Transaction required). I found an older post on this forum and tried the same fix but didnt work. I dont have hibernate validation on my classpath. Am using Hibernate 3.
My test is as follows,
public class ProviderManagerTest extends TestCase {
Context context;
/**
* Bootstrap the Embedded EJB Container
*
* #throws Exception
*/
protected void setUp() throws Exception {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
p.put("log4j.category.OpenEJB.options ", " debug");
p.put("RcsDB", "new://Resource?type=DataSource");
p.put("RcsDB.JdbcDriver", "oracle.jdbc.driver.OracleDriver");
p.put("RcsDB.JdbcUrl", "jdbc:oracle:thin:#dbserver:1521:ttv");
p.put("RcsDB.JtaManaged", "true");
p.put("RcsDB.JtaManaged", "true");
p.put("RcsDB.username", "username");
p.put("RcsDB.password", "password");
context = EJBContainer.createEJBContainer(p).getContext();
context.bind("inject", this);
}
#Test
public void testWithTransaction() throws Exception {
Caller transactionalCaller = (Caller) context.lookup("java:global/cms_epgmgmt/TransactionBean");
transactionalCaller.call(new Callable() {
public Object call() throws Exception {
Provider testProvider = new Provider();
testProvider.setName("test");
IProviderManager providerManager = null;
providerManager = (IProviderManager) context.lookup("java:global/cms_epgmgmt/ProviderManager");
providerManager.create(testProvider);
return null;
}
});
}
/*private void testProviderCreation()
{
Provider testProvider = new Provider();
testProvider.setName("test");
providerManager.create(testProvider);
}
*/
public static interface Caller {
public <V> V call(Callable<V> callable) throws Exception;
}
/**
* This little bit of magic allows our test code to execute in
* the scope of a container controlled transaction.
*/
#Stateless
#TransactionAttribute(REQUIRES_NEW)
public static class TransactionBean implements Caller {
public <V> V call(Callable<V> callable) throws Exception {
return callable.call();
}
}
}
where provider manager is as below,
#Local(IProviderManager.class)
#Stateless
public class ProviderManager implements IProviderManager{
#PersistenceContext(unitName = "epgmanagerjpaunit")
private EntityManager entityManager;
public void create(Provider provider)
{
entityManager.persist(provider);
}
}
Thanks in advance,
-v-

Categories

Resources