I am trying to mock enum using powerMock but got Field 'fTestClass' was not found in class error when i ran test. I found that the issue is with Junit 4.12 and powermock-module-junit4 1.5.6. so I changed to 1.6.1 now I am getting below error ...
java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor9.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:45)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:142)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:61)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:109)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:57)
at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)
at OrderEventProcessorTest.setUp(OrderEventProcessorTest.java:47)
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:497)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:133)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.NullPointerException
Basically I am trying to mock enum to check the functionality of insert, update, delete operations to cassandra db. the enum gives setups the cassadra db connection. I want to mock it so I don't need to connect to the DB to test my crud functionality. Please let me know if still is there any versioning issues with Junit 4.12 and powermock 1.6.1 . I am using mockito-core 1.10.19 and maven-surefire-plugin 2.19.1
EDITED
ENUM for DB connection
public enum CassProvider {
INSTANCE;
private Map<String,ThreadLocal<PreparedStatement>> psMap;
private String[] hostnames;
private String username;
private String password;
private String keyspace;
private Cluster cluster;
private Session session;
private CassProvider() {
init();
psMap = createPreparedStatements();
}
private void init() {
//get host, port, user , pasword from properties file
cluster = Cluster.builder().addContactPoints(hostnames).withPort(port).withCredentials(username, password).build();
session = cluster.connect(keyspace);
}
private static Map<String,ThreadLocal<PreparedStatement>> createPreparedStatements() {
//code goes for mapping preparedStatements
return psMap;
}
public PreparedStatement getPreparedStatement(String id) {
//logic for preparedStatement
return preparedStatement;
}
public Session getSession() {
return session;
}
}
Code I would like to test for different conditions it executes different prepared statements
if (eventMappingType != null && processEvent) {
.......
BatchStatement batchStatement = new BatchStatement();
PreparedStatement psFieldInsert = CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_FV");
if (eventMappingType.getSimpleFields() != null) {
for (FieldType fieldType : eventMappingType.getSimpleFields().getField()) {
Object value = MVEL.executeExpression(fieldType.getSerializedExpr(), context);
batchStatement.add(psFieldInsert.bind(keyFields.get("orderNumber"),dateStringToDate(eventDateTime), fieldType.getValue(), value != null ? value.toString() : value));
}
}
if (eventType.compareToIgnoreCase("OrderPlaced") == 0) {
//Update the lookup table for given name 2 orders.
if (name != null && name.compareToIgnoreCase("")!=0) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_BY_NAME").bind(name, dateStringToDate(eventDateTime), orderNumber));
}
//Update the lookup table for accIds 2 orders; not sure if we need this for now
if (accIds != null && accIds.compareToIgnoreCase("")!=0) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_ORDERS_BY_ACCIDS").bind(accIds, dateStringToDate(eventDateTime), orderNumber));
}
if (SAPOrderNumber != null) {
batchStatement.add(CassProvider.INSTANCE.getPreparedStatement("INSERT_SAP_ORDER").bind(SAPOrderNumber, orderNumber));
}
}
CassProvider.INSTANCE.getSession().execute(batchStatement);
}
Not sure how your Cluster.builder() method works but I suggest you make that you configurable, i.e. to open it up for your test class to inject a mocked builder that in the end returns a mocked Cluster that in turn returns a mocked Session...
Related
I work on a small educational project - easy java app with database and gui. I work in NetBeans IDE.
For graphical interface I use JavaFX, and as I've testet this part work perfectly fine, but I have some problem with JDBC part (I use JDBC driver for sqlite database, created with DB browser for sqlite). My main application class looks like this:
public class BazaLyoko extends Application {
#Override
public void start(Stage stage) throws Exception {
Database baza = new Database();
String tytul = baza.getEpisodeName(1);
stage.setTitle(tytul);
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And when I change those lines:
Database baza = new Database();
String tytul = baza.getEpisodeName(1);
To this (to replace value retrieved from database to a placeholder - I did this to ensure if the error is rather connected with JavaFX or JDBC part)
String tytul = "";
Program start without problem, but when I try to use my database application don't start. There isn't any compilation error or anything like that (or maybe I just don't see them, as I'm quite new to this IDE, though I think such things are usually blatantly visible) just no application window appear.
Here's the code for my database class(they both share the same package):
public class Database {
public static Connection conn;
public Database()
{
connect();
}
public static void connect()
{
String connectionString = "jdbc:sqlite:BazaLyoko.db";
try
{
conn = DriverManager.getConnection(connectionString);
if (conn != null)
{
DatabaseMetaData meta = conn.getMetaData();
//System.out.println("Nazwa sterownika to " + meta.getDriverName());
//System.out.println("Stworzono baze danych.");
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
private ResultSet doQuery(String query) throws SQLException
{
Statement stmt = null;
try
{
stmt = this.conn.createStatement();
ResultSet result = stmt.executeQuery(query);
return result;
}
catch (SQLException e )
{
throw new Error("Problem", e);
}
finally
{
if (stmt != null) { stmt.close(); }
}
}
public String getEpisodeName(int nr) throws SQLException
{
ResultSet result = doQuery("SELECT tytul FROM Odcinki WHERE numer="+String.valueOf(nr));
result.next();
return result.getString("tytul");
}
}
Database of that name is located inside my project directory (i also tried to copy it to package directory but nothing changed), the names of the table and column are correct to and exist a row with value 1 in column numer.
What I'm missing or doing wrong?
Edit:
I manage to get the following Stack Trace:
No suitable driver found for jdbc:sqlite:BazaLyoko.db
at com.sun.corba.se.impl.util.Utility.printStackTrace(Utility.java:933)
at bazalyoko.Database.connect(Database.java:46)
at bazalyoko.Database.<init>(Database.java:26)
at bazalyoko.BazaLyoko.start(BazaLyoko.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Thread.java:748)
Exception in Application start method
java.lang.reflect.InvocationTargetException
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 com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
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 sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at bazalyoko.Database.doQuery(Database.java:57)
at bazalyoko.Database.getEpisodeName(Database.java:75)
at bazalyoko.BazaLyoko.start(BazaLyoko.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
... 1 more
Exception running application bazalyoko.BazaLyoko
Java Result: 1
am working with spring boot and mongoDB. have written the repository for my model and have written my own logic to increment id by using mongo inc. while doing
gradle test
the tests are failing with the following exception.
org.springframework.data.mapping.model.MappingException: Cannot use a complex object as a key value.
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeMapInternal(MappingMongoConverter.java:669)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.createMap(MappingMongoConverter.java:585)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writePropertyInternal(MappingMongoConverter.java:471)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:430)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:418)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:322)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:418)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:392)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:356)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:79)
at org.springframework.data.mongodb.core.MongoTemplate.toDbObject(MongoTemplate.java:853)
at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1014)
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:963)
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:80)
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.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy94.save(Unknown Source)
at org.springframework.data.repository.CrudRepository$save.call(Unknown Source)
at com.auth.mongo.impl.ApplicationRepositoryImpl.save(ApplicationRepositoryImpl.groovy:26)
at com.auth.repository.ApplicationRepository$save$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
can any one suggest me what am doing wrong
EDIT:
FOR Example: Application Class is the domain
class Application implements Serializable {
String id
APIKey apiKey
Map actions = [:]
Application() {
}
Application(APIKey apiKey) {
this.apiKey = apiKey
List customerActionsList = [] // added some actions
actions.put(Role.User, customerActionsList)
}
APIKey:
String apiKey
String application
DateTime whenCreated
boolean active
APIKey() {
}
APIKey(String application, DateTime whenCreated, boolean active) {
this.apiKey = generateAPIKey(application)
this.application = application
this.whenCreated = whenCreated
this.active = active
}
repository class is as follows:
#Component
class ApplicationRepositoryImpl implements ApplicationRepository {
private final Logger logger = LoggerFactory.getLogger(ApplicationRepositoryImpl.class)
#Autowired
ApplicationRepositoryMongo applicationRepositoryMongo
#Autowired
SequenceRepository sequenceRepository
#Override
Serializable save(Application application) {
application.id = application.id?:sequenceRepository.getNextSequenceId(Application.simpleName).sequence
return applicationRepositoryMongo.save(application).id
}
#Override
Application find(String id) {
return applicationRepositoryMongo.findOne(id)
}
I am incrementing the id of Application class as follows
public SequenceId getNextSequenceId(String type) {
//get sequence type
Query query = new Query(Criteria.where("id").is(type))
//increase sequence id by
Update update = new Update()
update.inc('sequence', 1)
//return new increased i
FindAndModifyOptions options = new FindAndModifyOptions()
options.returnNew(true)
//this is the magic happened
SequenceId seqId = mongoOperation.findAndModify(query, update, options, SequenceId.class)
return seqId
}
While saving the domain object getting the above exception. I have done all mongo configuration. the configuration is working for other domains.
There's an open Improvement in Spring Don't require Converters for Complex classes that are used as Ids. Currently Spring decided to not support it.
decided not to support it at all
I am writing a JUnit test case for a method which internally invokes another method through interface. I am using Mockito to mock the interface but for some reason it gives me NPE. I debugged through but wasn't able to get any clue to fix it. getAllVendors() method throws exception which comes through an Interface.
MUT
public void prepare() throws AccountServiceException, ManagerException {
vendors = getVendorManager().getAllVendors();
microsites = new ArrayList<VendorMicrositeTO>();
microsites.add( new VendorMicrositeTO( "http://www.docusign.com", "docuSign" ) );
clientUser = createClientUserObject();
}
JUnit
#Test
public void testPrepare() throws Exception {
AccountAction accountAction = new AccountAction();
Map<String, Object> actionMap = new HashMap<>();
actionMap.put("application", "ESignatureIntegrationAction");
ActionContext.setContext(new ActionContext(actionMap));
String beanName = Constants.VENDOR_MANAGER_SPRING_BEAN;
PowerMockito.mockStatic(AppContext.class);
PowerMockito.when(AppContext.containsBean( beanName )).thenReturn( true );
IVendorDto iVendorDto = new VendorDto();
iVendorDto.setActive(true);
iVendorDto.setCreatedBy("9/15/2016");
iVendorDto.setName("CorpESignClientUser");
iVendorDto.setCreatedBy("SYSTEM");
List<IVendorDto> vendorList = new ArrayList<>();
vendorList.add(iVendorDto);
IVendorManager iManager = Mockito.mock((IVendorManager.class));
Mockito.when(iManager.getAllVendors()).thenReturn(vendorList);
accountAction.setVendors(vendorList);
accountAction.prepare();
}
Stack trace
java.lang.NullPointerException
at com.mercuryinsurance.esignature.ui.webapp.action.AccountAction.prepare(AccountAction.java:65)
at test.com.mercuryinsurance.esignature.ui.webapp.action.TestAccountAction.testPrepare(TestAccountAction.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
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)
Thanks, in advance
Seems you forgot to add a line in your test like:
accountAction.setVendorManager(iManager);
So yeah, I have been tackling a very similar issue.
This usecase is a logical outcome of the application of the SOLID principles within an IoT based application. If you decouple the layers of your application using interfaces and are testing an innner layer you are bound to come across testing an interface whose implementations have more interface dependencies.
You can achieve this goal using two testing angles combined
Use the Parameterized JUnit runner to launch the one set of unit tests for all of the implementations.
Then internally during each run initialize the mocked dependencies using Mockito
For more information on Parameterized testing (that's where i originally found it) be sure to visit this post. The manual initialization of mockito was something i found here.
All and all the resulting code looks like this:
#RunWith(Parameterized.class)
public class YourInterfaceTest {
#Mock
private ImplementationDependency sneakyBreakyNpeAvoided;
#InjectMocks
private YourInterfaceToTest iface;
// constructor is used by the Parameterized runner to provide impelementations
public YourInterfaceTest (YourInterfaceToTest ifaceToTest) {
this.iface = ifaceToTest;
}
// this method is called always before running tests so a good time to inject anything
#Before
public void init() {
MockitoAnnotations.initMocks(this);
Mockito.when(sneakyBreakyNpeAvoided.returnTrue()).thenReturn(true);
}
#Test(expected = IllegalArgumentException.class)
public void doSomething_nullParameter_throwsIllegalArgumentException() {
Assert.fail(); // tests here :)
}
#Parameterized.Parameters
public static Collection<YourInterfaceToTest > provideImplementations() {
// change to Arrays.asList when multiple implementations are available
return Collections.singletonList(new YourInterfaceImpl());
}
}
Hope I understood the OP's issue well.
This questions has been asked a few times but they all are using the #Configuration annotation. For what I am doing this is not necessary. I am using the singleton pattern to create a connection to my database. However I am getting the following error:
[ERROR] com.htd.aop.logging.LoggingAspect - Exception in com.htd.web.rest.PoResource.generateJobTicket() with cause = null
java.lang.NullPointerException: null
at com.htd.config.DataSourceDAO.<init>(DataSourceDAO.java:24) ~[classes/:na]
at com.htd.config.DataSourceDAO.getInstance(DataSourceDAO.java:35) ~[classes/:na]
at com.htd.repository.PoDataSource.<init>(PoDataSource.java:12) ~[classes/:na]
at com.htd.web.rest.util.createJobTicket.<init>(createJobTicket.java:16) ~[classes/:na]
at com.htd.web.rest.PoResource.generateJobTicket(PoResource.java:339) ~[classes/:na]
at com.htd.web.rest.PoResource$$FastClassBySpringCGLIB$$cfcd338a.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at com.htd.aop.logging.LoggingAspect.logAround(LoggingAspect.java:49) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_31]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_31]
The error is telling to me look at line 24 on my DataSourceDAO class because it is null. It is referring to the following:
// Step 1: JDBC props
String DB_URL = env.getProperty("spring.datasource.url");
String USER = env.getProperty("spring.datasource.username");
String PASS = env.getProperty("spring.datasource.password");
Full code:
public class DataSourceDAO {
#Inject
private Environment env;
private static DataSourceDAO instance;
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
// Step 1: JDBC props
String DB_URL = env.getProperty("spring.datasource.url");
String USER = env.getProperty("spring.datasource.username");
String PASS = env.getProperty("spring.datasource.password");
private DataSourceDAO() { }
public static DataSourceDAO getInstance() {
if (instance == null) {
synchronized (DataSourceDAO.class) {
if (instance == null) {
instance = new DataSourceDAO();
}
}
}
return instance;
}
public java.sql.Connection getConnection() throws ClassNotFoundException,
SQLException {
Class.forName("com.mysql.jdbc.Driver");
if (conn == null) {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
}
return conn;
}
}
I am not sure why it would be null. #Inject should work fine, or so I thought.
First of all you won't get anything injected in a class that you are instancing manually.
After you fixed the manual initialization of the class you should note that inside the constructor you won't have your injected properties available, they're all set after instantiation.
If you want to do some behaviour after instancing the object you should use #PostConstruct callback (http://www.mkyong.com/spring/spring-postconstruct-and-predestroy-example/)
I have an J2EE project in java ee 6 framework. with EJB and War module.
I want to add a Service to EJB module to manipulate some data in data base , so i need to access the DAO methods in Service methods . but it return error!
#WebService(serviceName = "AddUserService")
#Stateless()
public class AddUserService {
#PersistenceContext(unitName = "UserRegistrationService-ejbPU")
EntityManager em;
#WebMethod(operationName = "registerUser")
public String registerUser(BasicUserInfo basicUserInfo) {
UserEJB userEJB=new UserEJB(em);
String retValue = "";
User user = new User();
user.setAge(basicUserInfo.getAge());
user.setUserName(userName);
userEJB.addUser(user);
retValue = " User Registered with user_ID:" + user.getId().toString() + " and userName:" + user.getUserName();
return retValue;
}
}
the EJB class codes are :
#TransactionManagement(TransactionManagementType.CONTAINER)
#Stateless
public class UserEJB {
#PersistenceContext(unitName = "UserRegistrationService-ejbPU")
EntityManager em;
public UserEJB() {
}
public UserEJB(EntityManager em) {
this.em = em;
}
public void addUser(User user) {
em.persist(user);
}
}
testing the service make this error on the server:
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at dao.UserEJB.addUser(UserEJB.java:34)
at app.Services.AddUserService.registerUser2(AddUserService.java:60)
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.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
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 com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
Your EntityManger doesn't get injected by the container because you've create the UserEJB object by yourself! You've broken the injection chain. When using DI you must let the container create the object for you. Try this way:
#WebService(serviceName = "AddUserService")
#Stateless()
public class AddUserService {
//actually you don't need this here, you'll get that injected inside the UserEJB
#PersistenceContext(unitName = "UserRegistrationService-ejbPU")
EntityManager em;
#Inject
UserEJB userEjb;
#WebMethod(operationName = "registerUser")
public String registerUser(BasicUserInfo basicUserInfo) {
//you don't need this line, the container will instantiate the object for you!
//UserEJB userEJB=new UserEJB(em);
String retValue = "";
User user = new User();
user.setAge(basicUserInfo.getAge());
user.setUserName(userName);
userEJB.addUser(user);
retValue = " User Registered with user_ID:" + user.getId().toString() + " and userName:" + user.getUserName();
return retValue;
}
}
The error is inside class UserEJB.java at line 34, so please post that code.