No tx on thread CMP OpenEJB4 JUnit Hibernate - java

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-

Related

Java NullPointerException with Mocked Object

I have a unit test I am writing for a class, and this class uses a ConfigurationManager I wrote to get configuration from a TOML object (and therefore from a TOML file).
The Code
Here is the relevant ConfigurationManager code:
public class ConfigurationManager {
// DEFAULT_LOGGING_LEVEL should represent level to use in production environment.
private final static Level DEFAULT_LOGGING_LEVEL = Level.FINE;
private final static String LOG_LEVEL_ENV_PROPERTY = "LOG_LEVEL";
private final static String TOML_FILE_NAME = "config.toml";
private final static String LOCAL_ENV_PROPERTY = "local";
private final static String ENV_PROPERTY = "MY_ENV";
private static Logger CM_LOGGER;
private Environment environment;
public ConfigurationManager() {
environment = new Environment();
CM_LOGGER = new LoggerUtil(ConfigurationManager.class.getName(), getLoggingLevel()).getLogger();
}
public File getTomlFile() throws URISyntaxException, FileNotFoundException {
URI uri = getConfigURI();
File tomlFile = new File(uri);
if (!tomlFile.exists()) {
String err = TOML_FILE_NAME + " does not exist!";
CM_LOGGER.severe(err);
throw new FileNotFoundException(err);
}
return tomlFile;
}
/**
* #return A URI representing the path to the config
* #throws URISyntaxException if getConfigURI encounters bad URI syntax.
*/
private URI getConfigURI() throws URISyntaxException {
return getClass().getClassLoader().getResource(TOML_FILE_NAME).toURI();
}
/**
* Method for getting the app configuration as a toml object.
*
* #return A toml object built from the config.toml file.
* #throws URISyntaxException if getConfigURI encounters bad URI syntax.
* #throws FileNotFoundException if getTomlFile can't find the config.toml file.
*/
public Toml getConfigToml() throws URISyntaxException, FileNotFoundException {
return new Toml().read(getTomlFile());
}
}
And here is the code that calls this Configuration Manager:
public class Listener {
// Initializations
private static final String CONFIG_LISTENER_THREADS = "listenerThreads";
private static final String DEFAULT_LISTENER_THREADS = "1";
/**
* Constructor for getting app properties and initializing executor service with thread pool based on app prop.
*/
#PostConstruct
void init() throws FileNotFoundException, URISyntaxException {
ConfigurationManager configurationManager = new ConfigurationManager();
int listenerThreads = Integer.parseInt(configurationManager.getConfigToml()
.getString(CONFIG_LISTENER_THREADS, DEFAULT_LISTENER_THREADS));
this.executorService = Executors.newFixedThreadPool(listenerThreads);
LOGGER.config("Listener executorService threads: " + listenerThreads);
}
...
}
And here is the test for that code (See comment to see where NPE is triggered):
public class ListenerTests {
#Mock
ConfigurationManager mockCM;
#InjectMocks
Listener listener = new Listener();
#Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
#Test
public void testListener_ShouldInit() throws FileNotFoundException, URISyntaxException {
when(mockCM.getConfigToml().getString(any(), any())).thenReturn("5"); // !!!NPE TRIGGERED BY THIS LINE!!!
listener.init();
verify(mockCM, times(1)).getConfigToml().getString(any(), any());
}
}
The Problem
I get a NullPointerException as follows
java.lang.NullPointerException
at com.bose.source_account_listener.ListenerTests.testListener_ShouldInit(ListenerTests.java:37)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I have a guess as to the problem here but I'm not sure how to validate my guess. My guess is that I am mocking the ConfigurationManager, but the mock doesn't know that the ConfigurationManager can generate a TOML file which has a getString method, so I end up getting the NPE. This makes me think that I need a mock TOML for my mock ConfigurationManager, but I am neither certain this is the case or that this is the proper solution.
I am new to Mockito and Java in general so any help would be appreciated.
You need to mock every bit of your call, not just the full call. mockCM.getConfigToml() has no mock response, so it returns null, and a toString is invoked on a null object. Your options are to return a non-mocked "Toml" or mock a Toml and then set that up with a when configuration.
Toml tomlMock = Mockito.mock(Toml.class);
when(mockCM.getConfigToml()).thenReturn(tmolMock);
when(tmolMock.getString(any(), any())).thenReturn("5");
You're trying to mock the method of what is returned by calling getConfigToml. That is, you need to mock the object of what should be returned by getConfigToml, and then call getString on that object.

Write junit for a final class using #postconstruct using mockito

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.

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();
}

PowerMock - NPE on #PrepareForTest

Problem: The instrumentation class in PowerMock isn't being initialized. I'm loading the library through the #Rule annotation. I've got the VM argument in place:
-javaagent:project_path/libs/powermock-module-javaagent-1.5.jar
When I walk through with the debugger, PowerMockAgent#premain gets called and the instrumentation object gets set, but when it's called during the test setup, the instrumentation object is null, throwing the error below.
Why is the instrumentation variable not keeping it's value between when PowerMockAgent#premain is called and when PowerMockClassRedefiner.redefine calls it?
Instrumentation gets set correctly here on load:
private static void initialize(String agentArgs, Instrumentation inst) throws IOException {
instrumentation = inst;
inst.addTransformer(new DefinalizingClassTransformer(), false);
inst.addTransformer(classTransformer, true);
}
But when called again from #PrepareForTest({ Logger.class }), is null
public class PowerMockClassRedefiner {
public static void redefine(Class<?> cls) {
if(cls == null) {
throw new IllegalArgumentException("Class to redefine cannot be null");
}
PowerMockAgent.getClasstransformer().setClassesToTransform(Arrays.asList(cls.getName()));
try {
PowerMockAgent.instrumentation().retransformClasses(cls);
} catch(Exception e){
throw new RuntimeException("Failed to redefine class "+cls.getName(), e);
}
}
Resulting in error:
java.lang.RuntimeException: Failed to redefine class com.testapp.Logger
at org.powermock.modules.agent.PowerMockClassRedefiner.redefine(PowerMockClassRedefiner.java:33)
at org.powermock.modules.agent.PowerMockClassRedefiner.redefine(PowerMockClassRedefiner.java:42)
at com.testapp.testFramework.PowerMockRuleAgentSetup.redefine(PowerMockRuleAgentSetup.java:29)
at com.testapp.testFramework.PowerMockRuleAgentSetup.initialize(PowerMockRuleAgentSetup.java:19)
at com.testapp.testFramework.PowerMockOverriderRule.apply(PowerMockOverriderRule.java:19)
at org.junit.runners.BlockJUnit4ClassRunner.withMethodRules(BlockJUnit4ClassRunner.java:341)
at org.junit.runners.BlockJUnit4ClassRunner.withRules(BlockJUnit4ClassRunner.java:330)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:248)
at com.xtremelabs.robolectric.RobolectricTestRunner.methodBlock(RobolectricTestRunner.java:287)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
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)
Caused by: java.lang.NullPointerException
at org.powermock.modules.agent.PowerMockClassRedefiner.redefine(PowerMockClassRedefiner.java:31)
... 22 more
Here's my test setup:
#RunWith(RobolectricTestRunner.class)
#PrepareForTest({ Logger.class }) // THIS IS WHERE THE ERROR GETS THROWN
public class LoggerTest {
#Rule public PowerMockOverriderRule rule = new PowerMockOverriderRule();
public LoggerConfig config;
#Before
public void setUp() {
config = mock(LoggerConfig.class);
}
UPDATE:
Removing the #RunWith(RobolectricTestRunner.class) fixes the problem, but isn't an option for my project. (It's an Android project).
I'm sorry to ask but why would you even want to mock a Logger class? If you want to ensure that the output is logged to the console you can wrap a logger in an abstraction that you can mock.
class LogWraper {
void someMethod() {
logger.log()
}
}
and then you can create a mock of your FooWraper. No need to use Powermock at all...

PowerMock - Mocking static system class throws IllegalStateException

I have the following code
public class A{
public void createFile() {
File tempXmlFile = null;
String extension = ".xml";
String name = "someName";
try {
tempXmlFile = File.createTempFile(name, extension);
if (tempXmlFile.exists()) {
tempXmlFile.delete();
}
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(A.class)
public class testA extends TestCase{
private A classUnderTest;
#Override
#Before
public void setUp() {
classUnderTest = PowerMock.createMock(A.class); //the class is more complex in my case and I have to mock it
}
public void testCreateFile() throws IOException{
String extension = ".xml";
String name = "someName";
PowerMock.mockStatic(File.class);
File tempFileMock = PowerMock.createMock(File.class);
expect(File.createTempFile(name, extension)).andReturn(tempFileMock);
expect(tempFileMock.exists()).andReturn(true);
expect(tempFileMock.delete()).andReturn(true);
replay(File.class, tempFileMock, classUnderTest);
classUnderTest.createFile();
verify(File.class, tempFileMock, classUnderTest);
}
}
In the test class as I said the class under test must be mocked(I can't create a new object).
When I run the test I get:
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:174)
at org.easymock.EasyMock.expect(EasyMock.java:156)
at myPackage.testA.testCreateFile(testA.java:35)
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 org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:163)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:113)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:111)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:87)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:44)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
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 read the documentation here http://code.google.com/p/powermock/wiki/MockSystem but the test stil wont't work. Am I missing something?
Edit: I tested the previous code with a real A object (and removed it from replay)
classUnderTest = new A();
but I still get the same exception.
Try adding File.class to #PrepareForTest.
try the org.powermock.reflect.internal.WhiteboxImpl.newInstance() method to create the object of the class and then call method directly.
1) this will suppress the constructor of the class
2) if your class contains static block then use suppressStaticInitilaizationFor to suppress that.
regards
Anil Sharma
Add File.class to #PrepareForTest and check the imports of replay and verify. They should be from PowerMock.
I think you need to suppress constructor
Check this
http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior

Categories

Resources