i spy a object to test a method
List<HighWay> mockedList = mock(List.class);
request = Mockito.spy(new HighWayRequest());
Mockito.doReturn(mockedList).when(request).getHighWays();
request.updateNewHighWay(repository);
the updateNewHighWay method invoke getHighWays method which i want to return list,
and real method of request is like that
public void updateNewHighWay(HighWayRepository repository) {
List<HighWay> total = getHighWays();
List<HighWay> willSave = new ArrayList<HighWay>();
for (HighWay highWay : total) {
if (!repository.exists(highWay.getId())) {
willSave.add(highWay);
repository.save(highWay);
}
}
while (total.size() == willSave.size()) {
total = getHighWays();
willSave = new ArrayList<HighWay>();
for (HighWay highWay : total) {
if (!repository.exists(highWay.getId())) {
willSave.add(highWay);
repository.save(highWay);
}
}
}
}
public List<HighWay> getHighWays() {
// TODO Auto-generated method stub
return null;
}
but the reality it throws nullexception.
java.lang.NullPointerException at
chinahighway.HighWayRequest.updateNewHighWay(HighWayRequest.java:206)
at chinahighway.HttpTest.testpageinsert(HttpTest.java:269) 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.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.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at
org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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)
why the doReturn not work? how to let getHighWays method return my wanted list?
plz help me thanks very much!
Related
I would appreciate any hints on the following problem I've encountered. While unit testing multipart file upload service method in Spring Reactive WebFlux app, I am getting NPE for reactor.core.publisher.MonoWhen$WhenCoordinator as follows
java.lang.NullPointerException
at reactor.core.publisher.MonoWhen$WhenCoordinator.subscribe(MonoWhen.java:149)
Complete log is listed below as well.
Test :
#RunWith(SpringRunner.class)
#SpringBootTest
public class FileServiceTest2 {
#MockBean
private UploadedImageRepository uploadedImageRepository;
...
#Test
public void assembleImageTest() {
UploadedImage ui1 = new UploadedImage("1", "ui1.png");
UploadedImage ui2 = new UploadedImage("2", "ui2.png");
FilePart filePart1 = mock(FilePart.class);
FilePart filePart2 = mock(FilePart.class);
given(this.uploadedImageRepository.save(ui1))
.willReturn(Mono.just(ui1));
given(this.uploadedImageRepository.save(ui2))
.willReturn(Mono.just(ui2));
given(this.uploadedImageRepository.findAll())
.willReturn(Flux.just(ui1, ui2));
given(filePart1.filename())
.willReturn(ui1.getImageName());
given(filePart1.transferTo(any()))
.willReturn(Mono.empty());
given(filePart2.filename())
.willReturn(ui2.getImageName());
given(filePart2.transferTo(any()))
.willReturn(Mono.empty());
Flux<FilePart> files = Flux.just(filePart1, filePart2);
StepVerifier.create(this.uploadService.createFile(files))
.verifyComplete();
}
Under test :
#Service
public class UploadService {
Mono<Void> createFile(Flux<FilePart> fileParts) {
return fileParts.flatMap(part -> {
Mono<UploadedImage> savedToDBImage = this.uploadedImageRepository.save(
new UploadedImage(UUID.randomUUID().toString(), part.filename()))
.log("createFile-fileSavedToDB"); // NPE!
Mono<Void> copiedFile = Mono.just(Paths.get(UPLOAD_URL, part.filename()).toFile())
.log("createFile-pathAssembled")
.doOnNext(destinationFile -> {
try {
destinationFile.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.log("createFile-fileAssembled")
.flatMap(part::transferTo)
.log("createFile-fileCopied");
return Mono.when(savedToDBImage, copiedFile)
.log("createFile-monoWhen");
})
.log("createFile-flatMap")
.then()
.log("createFile-done");
}
UploadedImage class (w Lombok) :
#Data
#RequiredArgsConstructor
#NoArgsConstructor
public class UploadedImage {
#NonNull private String id;
#NonNull private String imageName;
}
SpringData Reactive Repository:
#Repository
public interface UploadedImageRepository extends ReactiveCrudRepository<UploadedImage, String> {
}
Logs are as follows:
java.lang.NullPointerException
at reactor.core.publisher.MonoWhen$WhenCoordinator.subscribe(MonoWhen.java:149)
at reactor.core.publisher.MonoWhen.subscribe(MonoWhen.java:99)
at reactor.core.publisher.MonoOnAssembly.subscribe(MonoOnAssembly.java:76)
at reactor.core.publisher.MonoLogFuseable.subscribe(MonoLogFuseable.java:53)
at reactor.core.publisher.Mono.subscribe(Mono.java:3080)
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:372)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onNext(FluxPeekFuseable.java:198)
at reactor.core.publisher.FluxArray$ArraySubscription.slowPath(FluxArray.java:118)
at reactor.core.publisher.FluxArray$ArraySubscription.request(FluxArray.java:91)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.request(FluxPeekFuseable.java:138)
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onSubscribe(FluxFlatMap.java:332)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:172)
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53)
at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59)
at reactor.core.publisher.FluxLogFuseable.subscribe(FluxLogFuseable.java:53)
at reactor.core.publisher.FluxFlatMap.subscribe(FluxFlatMap.java:97)
at reactor.core.publisher.FluxLog.subscribe(FluxLog.java:50)
at reactor.core.publisher.MonoIgnoreElements.subscribe(MonoIgnoreElements.java:37)
at reactor.core.publisher.MonoLog.subscribe(MonoLog.java:51)
at reactor.core.publisher.Mono.subscribe(Mono.java:3080)
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:728)
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:700)
at reactor.test.DefaultStepVerifierBuilder.verifyComplete(DefaultStepVerifierBuilder.java:566)
at pb.sl.UploadService.createFile(FileServiceTest2.java:112)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
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)
Looking more closely, I think you're not mocking your repository as expected, and in your test the repository call returns null.
You're not using a Mockito argument matcher but a concrete instance for the argument. Later in your service implementation, this method is called, but with a different instance. My guess is Mockito is using equals to check if the given matches that mock call - maybe your UploadedImage could be improved in that regard?
given(this.uploadedImageRepository.save(ui1)) should be:
given(this.uploadedImageRepository.save(any()))
.willAnswer(invocation -> Mono.just(invocation.getArgument(0)))
I am using Spark to write data to Hbase, I can read data just fine but write is failing with following exception. I found similar issue that got resolved by adding *site.xml and hbase JARs. But it is not working for me. I am trying to read data from a table write data to another table. i can read data just fine but getting exception while writing.
JavaPairRDD<ImmutableBytesWritable, Put> tablePuts = hBaseRDD.mapToPair(new PairFunction<Tuple2<ImmutableBytesWritable, Result>, ImmutableBytesWritable, Put>() {
#Override
public Tuple2<ImmutableBytesWritable, Put> call(Tuple2<ImmutableBytesWritable, Result> results) throws Exception {
byte[] accountId = results._2().getValue(Bytes.toBytes(COLFAMILY), Bytes.toBytes("accountId"));
String rowKey = new String(results._2().getRow();
String accountId2 = (Bytes.toString(accountId));
String prefix = getMd5Hash(rowKey);
String newrowKey = prefix + rowKey;
Put put = new Put( Bytes.toBytes(newrowKey) );
put.addColumn(Bytes.toBytes("def"), Bytes.toBytes("accountId"), accountId);
}
});
Job newAPIJobConfiguration = Job.getInstance(conf);
newAPIJobConfiguration.getConfiguration().set(TableOutputFormat.OUTPUT_TABLE, OUT_TABLE_NAME);
newAPIJobConfiguration.setOutputFormatClass(org.apache.hadoop.hbase.mapreduce.TableOutputFormat.class);
newAPIJobConfiguration.setOutputKeyClass(org.apache.hadoop.hbase.io.ImmutableBytesWritable.class);
newAPIJobConfiguration.setOutputValueClass(org.apache.hadoop.io.Writable.class);
tablePuts.saveAsNewAPIHadoopDataset(newAPIJobConfiguration.getConfiguration());
Exception in thread "main" java.lang.NullPointerException
at org.apache.hadoop.hbase.security.UserProvider.instantiate(UserProvider.java:123)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:214)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:119)
at org.apache.hadoop.hbase.mapreduce.TableOutputFormat.checkOutputSpecs(TableOutputFormat.java:177)
at org.apache.spark.internal.io.HadoopMapReduceWriteConfigUtil.assertConf(SparkHadoopWriter.scala:387)
at org.apache.spark.internal.io.SparkHadoopWriter$.write(SparkHadoopWriter.scala:71)
at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply$mcV$sp(PairRDDFunctions.scala:1083)
at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply(PairRDDFunctions.scala:1081)
at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply(PairRDDFunctions.scala:1081)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
at org.apache.spark.rdd.PairRDDFunctions.saveAsNewAPIHadoopDataset(PairRDDFunctions.scala:1081)
at org.apache.spark.api.java.JavaPairRDD.saveAsNewAPIHadoopDataset(JavaPairRDD.scala:831)
at com.voicebase.etl.s3tohbase.HbaseScan2.main(HbaseScan2.java:148)
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.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:879)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:197)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:227)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:136)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
I am using Apache POI for reading excel file (in xls and xlsx format).
It runs fine in IDE (I am using IntelliJ), but when I make the project to JAR, it can't read the excel file. I tried by giving full path of excel file, but not working.
File name spelling is right, file is not protected or read only format. Everything is good until I run JAR.
java.lang.reflect.InvocationTargetException
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 com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
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 sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/apache/poi/hssf/usermodel/HSSFWorkbook
at TakeInput.Take(TakeInput.java:25)
at MainGUI.main(MainGUI.java:53)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.apache.poi.hssf.usermodel.HSSFWorkbook
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 13 more
Exception running application MainGUI
Here is my TakeInput Class:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class TakeInput {
public void Take() throws Exception{
System.out.println("Inside TakeInput class..");
File f = new File("courses.xls");
FileInputStream fs = new FileInputStream(f);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
int CSECourseCounter=0;
for(int i=0;i<=sheet.getLastRowNum();i++){
String tempCode = sheet.getRow(i).getCell(0).getStringCellValue();
StringTokenizer tok = new StringTokenizer(tempCode);
String codeTok=tok.nextToken();
if(codeTok.equals("CSE") || codeTok.equals("CSI")) {
CSECourseCounter++;
}
}
CourseInfo[] courses = new CourseInfo[CSECourseCounter];
for(int i=0;i<CSECourseCounter;i++)
courses[i]=new CourseInfo();
System.out.println(sheet.getLastRowNum());
for(int i=0,j=0;i<=sheet.getLastRowNum();i++){
String tempCode = sheet.getRow(i).getCell(0).getStringCellValue();
StringTokenizer tok = new StringTokenizer(tempCode);
String codeTok=tok.nextToken();
if(codeTok.equals("CSE") || codeTok.equals("CSI")) {
courses[j].code = sheet.getRow(i).getCell(0).getStringCellValue();
courses[j].title = sheet.getRow(i).getCell(1).getStringCellValue();
courses[j].section = sheet.getRow(i).getCell(2).getStringCellValue();
courses[j].day = sheet.getRow(i).getCell(4).getStringCellValue();
courses[j].time = sheet.getRow(i).getCell(5).getStringCellValue();
//courses[i].room = sheet.getRow(i).getCell(6).getNumericCellValue();
//System.out.println(courses[j].code);
j++;
//CSECourseCounter++;
}
}
Arrays.sort(courses, new Comparator<CourseInfo>() {
#Override
public int compare(CourseInfo o1, CourseInfo o2) {
return o1.title.compareTo(o2.title);
}
});
System.out.println("CSE courses = "+CSECourseCounter);
for(int i=0;i<CSECourseCounter;i++){
courses[i].setCampus();
courses[i].setLabCLassAndTimeSlot();
courses[i].setDay();
}
//***************************** CourseInfo to a linked list ******************
for(int i=0;i<courses.length;i++){
CourseToLinkedList temp = AddSearchCourse.searchCourse(courses[i].code);
if(temp==null) {
AddSearchCourse.addCourse(courses[i].title,courses[i].code,courses[i].islabClass);
CourseToLinkedList temp1 = AddSearchCourse.searchCourse(courses[i].code);
temp1.addSections(courses[i].code,courses[i].title,courses[i].section,courses[i].day,courses[i].time,
courses[i].timeStart,courses[i].timeEnd,courses[i].room,
courses[i].faculty,courses[i].credit,courses[i].assigned,
courses[i].campus,courses[i].dept,courses[i].islabClass,
courses[i].timeSlot,courses[i].labTimeSlot,courses[i].day1,courses[i].day2
);
}
else{
CourseToLinkedList temp1 = AddSearchCourse.searchCourse(courses[i].code);
temp1.addSections(courses[i].code,courses[i].title,courses[i].section,courses[i].day,courses[i].time,
courses[i].timeStart,courses[i].timeEnd,courses[i].room,
courses[i].faculty,courses[i].credit,courses[i].assigned,
courses[i].campus,courses[i].dept,courses[i].islabClass,
courses[i].timeSlot,courses[i].labTimeSlot,courses[i].day1,courses[i].day2
);
}
}
System.out.println("outside try catch..");
}
}
I put a copy of this excel file which is in the project folder to that folder where JAR file situated. No problem with location.
As I can see the logs, this issue may happen because of dependency jars for your code. try to add the jar(may be 'jakarta-poi-version.jar') having class 'HSSFWorkbook' into your class path and then try to run it again.
I am learning the MVP architecture that google uses in their android codelabs. I have set up a simple example. Two input fields and a "+" button to show the addition result. The view is the main activity and I have a presenter that calls a service to add the two input values. The view passes itself to the presenter in the onCreate method and keeps a reference of the presenter as well.
View Interface:
public interface MainView {
String getFirstInput();
void showFirstInputError(int resId);
String getSecondInput();
void showSecondInputError(int resId);
void setResultText(int result);
}
Presenter method that is called when the button is pressed:
public void onResultClicked(){
String firstInput = view.getFirstInput();
String secondInput = view.getSecondInput();
if(firstInput.isEmpty()) {
view.showFirstInputError(R.string.num_input_error);
return;
}
if(secondInput.isEmpty()) {
view.showSecondInputError(R.string.num_input_error);
return;
}
Service service = new Service();
int result = service.add(Integer.getInteger(firstInput),
Integer.getInteger(secondInput));
view.setResultText(result);
}
Test:
#Test
public void shouldPopulateResultWhenButtonIsClicked() throws Exception {
when(view.getFirstInput()).thenReturn("3");
when(view.getSecondInput()).thenReturn("3");
when(service.add(3,3)).thenReturn(6);
presenter.onResultClicked();
verify(service).add(3,3);
verify(view).setResultText(6);
}
I get an error on the line the service is trying to add the two inputs.
presenter.onResultClicked();
int result = service.add(Integer.getInteger(firstInput),
Integer.getInteger(secondInput));
Can somebody please help. Thanks.
java.lang.NullPointerException
at com.example.ulidder.tdd_mvp_simple.MainPresenter.onResultClicked(MainPresenter.java:29)
at com.example.ulidder.tdd_mvp_simple.MainPresenterTest.shouldPopulateResultWhenButtonIsClicked(MainPresenterTest.java:46)
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.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.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
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)
It doesn't have anything to do with Android, Mockito or MVP, you're running a jUnit test, it's pure Java.
It's just a NullPointerException, nothing else. Go to line 29 of MainPresenter.java, add a breakpoint and launch the test in debug mode to see which method call is made on a null reference. Extract variables from chained calls if necessary.
I suspect that service.add(...) returns an java.lang.Integer and you're assigning it to an int. If it returns null, the unboxing will get you a NullPointerException at this line. Try assigning the return value to an Integer and debug the value. It may be null.
See this post for more information about unboxing of null values.
Hope this helps.
I am trying to import some guest layouts from a larFile(exported from another instance) in to a liferay instance (can be an already installed_and_configured OR can be a fresh installation) by creating a class which extends SimpleAction in a Start up Hook ( ) and then pointing 'application.startup.events' to this class in the portal-ext.properties file. I want this to run every time the server starts as my larFile version may change over the time. My Code is as follows...
File larFile=new File("/Users/grai001/Desktop/default_guest_public_new_light.lar");
//using absolute path for now -need help in accessing the relative path to ${liferay.home}??
Group guestGroup = GroupLocalServiceUtil.getGroup(1, GroupConstants.GUEST);
LayoutLocalServiceUtil.importLayouts(guestGroup.getCreatorUserId(), guestGroup.getGroupId(), false, new HashMap<String,String[]>(), larFile);
//I want them to be a public layouts which are visible to every one even when a user is not logged in - like the default WHAT-WE-DO kind ofpages in liferay6.1 - I am using 6.1GA2 at both ends
How ever this is giving me null pointer exception and the stack trace is as below..
com.liferay.portal.kernel.exception.SystemException: java.lang.NullPointerException
at com.liferay.portal.service.impl.LayoutLocalServiceImpl.importLayouts(LayoutLocalServiceImpl.java:1398)
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.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:122)
at com.liferay.portal.service.impl.LayoutLocalServiceVirtualLayoutsAdvice.invoke(LayoutLocalServiceVirtualLayoutsAdvice.java:197)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.service.impl.LayoutLocalServiceStagingAdvice.invoke(LayoutLocalServiceStagingAdvice.java:107)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.transaction.TransactionInterceptor.invoke(TransactionInterceptor.java:71)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.security.pacl.PACLAdvice.invoke(PACLAdvice.java:51)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ServiceBeanAopProxy.invoke(ServiceBeanAopProxy.java:211)
at $Proxy27.importLayouts(Unknown Source)
at com.liferay.portal.service.LayoutLocalServiceUtil.importLayouts(LayoutLocalServiceUtil.java:1037)
at com.walmart.services.mpportal.liferay.startup.StartupHook.run(StartupHook.java:88)
at com.liferay.portal.events.EventsProcessorImpl.processEvent(EventsProcessorImpl.java:106)
at com.liferay.portal.events.EventsProcessorImpl.process(EventsProcessorImpl.java:58)
at com.liferay.portal.events.EventsProcessorUtil.process(EventsProcessorUtil.java:53)
at com.liferay.portal.util.PortalInstances._initCompany(PortalInstances.java:462)
at com.liferay.portal.util.PortalInstances.initCompany(PortalInstances.java:92)
at com.liferay.portal.servlet.MainServlet.initCompanies(MainServlet.java:798)
at com.liferay.portal.servlet.MainServlet.init(MainServlet.java:355)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:649)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1585)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.NullPointerException
at com.liferay.portal.kernel.util.ParamUtil.getLong(ParamUtil.java:616)
at com.liferay.portal.service.impl.LayoutLocalServiceStagingAdvice.deleteLayout(LayoutLocalServiceStagingAdvice.java:70)
at com.liferay.portal.service.impl.LayoutLocalServiceStagingAdvice.invoke(LayoutLocalServiceStagingAdvice.java:113)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.transaction.TransactionInterceptor.invoke(TransactionInterceptor.java:71)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ChainableMethodAdvice.invoke(ChainableMethodAdvice.java:57)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.security.pacl.PACLAdvice.invoke(PACLAdvice.java:51)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:118)
at com.liferay.portal.spring.aop.ServiceBeanAopProxy.invoke(ServiceBeanAopProxy.java:211)
at $Proxy27.deleteLayout(Unknown Source)
at com.liferay.portal.service.LayoutLocalServiceUtil.deleteLayout(LayoutLocalServiceUtil.java:435)
at com.liferay.portal.lar.LayoutImporter.deleteMissingLayouts(LayoutImporter.java:196)
at com.liferay.portal.lar.LayoutImporter.doImportLayouts(LayoutImporter.java:774)
at com.liferay.portal.lar.LayoutImporter.importLayouts(LayoutImporter.java:147)
at com.liferay.portal.service.impl.LayoutLocalServiceImpl.importLayouts(LayoutLocalServiceImpl.java:1382)
... 50 more
And now doing LayoutLocalServiceUtil.importLayouts(guestGroup.getCreatorUserId(), guestGroup.getGroupId(), true, new HashMap<String,String[]>(), larFile);
ie...importing them as private layouts is working fine - unfortunately I want them to be public and be visible to every one. Also logging in as portal adminstrator and
importing from the UI as public layouts is working well and good. How ever I want this to be done in an automated way.
Trying to solve this problem of mine from the past 1 week - did enough research - but still couldn't. Any kind of help is appreciated..!
Thanks in advance
public void larTest() {
LiferayFacesContext liferayFacesContext = LiferayFacesContext
.getInstance();
ActionRequest request = (ActionRequest) liferayFacesContext
.getPortletRequest();
ThemeDisplay td = (ThemeDisplay) request
.getAttribute(WebKeys.THEME_DISPLAY);
long userId = td.getUserId();
long groupId = td.getScopeGroupId();
File larFile=new File("C:\\Users\\youssef\\dahar\\Downloads\\ok.lar");
//using absolute path for now -need help in accessing the relative path to ${liferay.home}??
Group guestGroup = null;
try {
guestGroup = GroupLocalServiceUtil.getGroup(groupId);
} catch (Exception e) {
System.out.println("catch 1");
e.printStackTrace();
}
try {
LayoutLocalServiceUtil.importLayouts(guestGroup.getCreatorUserId(), guestGroup.getGroupId(), false, new HashMap<String,String[]>(), larFile);
} catch (PortalException e) {
System.out.println("catch 2");
e.printStackTrace();
} catch (SystemException e) {
System.out.println("catch 3");
e.printStackTrace();
}
//I want them to be a public layouts which are visible to every one even when a user is not logged in - like the default WHAT-WE-DO kind ofpages in liferay6.1 - I am using 6.1GA2 at both ends
}
may be can help you this function
it worked for me sometimes and sometimes no :)