Android unit test skipping lines in tested class - java

I have a class with the following method:
/**
* #param contact
* #return
*/
public long create(Contact contact) {
ContentValues contactValues = buildContentValues(contact);
try {
return getDb().insert(CONTACTS_TABLE_NAME, null, contactValues);
} catch (SQLiteConstraintException sce) {
sce.printStackTrace(); // line 1
log.debug("Error inserting:" + contact, sce); //line2
return getDb().update(CONTACTS_TABLE_NAME, contactValues, COLUMN_ID + "=" + contact.userInfo.id, null); //line 3
}
}
I am running this using an AndroidTestCase as an Android Junit Test from Eclipse Android SDK. When I first started running it, my test was failing. When I stepped through it, it was handling the exception and running the update (marked as line 3).
Hmm...wonder why that is. So I added logging information and re-ran the unit test. When I step through the code, it goes directly to line 3 in the debugger without printing the stack trace. Strange, I think, but this is probably just some code stuck in the bin directory. So I run a project clean and run it again. EXACT same results.
It's a trick, I think. I set a breakpoint on line 3 AND line 1 and re-run the test. Test skips directly to line 3 without hitting the line 1 breakpoint.
Hmmm....Maybe the codes stuck in the bin directory and eclipse can't delete it with a clean. I've seen this happen before. So, I stop eclipse, go to the bin directory, and manually delete all of the files there. I then restart eclipse refresh the file system, run a project clean and then re-run my test. No change.
WTF?
Aha! I think, the code is stuck on the phone. I uninstall all of our software, including the test apps from the phone. Project->Clean and re-run the test. Still no change.
WTFF?
So, I think, I've tested on this phone so much, some code fragments stuck somewhere in there. I use the Android tool and build a fresh emulator. Project->Clean, run the test on the emulator. Exact same results.
FWTFF?
So, I wonder around aimlessly for a bit and have no ideas what to try next, so I'm posting here.
After this was posted, I spoke with a colleague and showed him the problem I was having. He has an eclipse setup slightly different than mine. He used my source and re-created the issue exactly.
FFFFF.

I think the defect was an optical illusion due to some bug. I changed the code to:
public long create(Contact contact) {
ContentValues contactValues = buildContentValues(contact);
long result;
try {
result = getDb().insert(CONTACTS_TABLE_NAME, null, contactValues);
} catch (SQLiteConstraintException sce) {
sce.printStackTrace();
log.debug("Error inserting:" + contact, sce);
result = getDb().update(CONTACTS_TABLE_NAME, contactValues, COLUMN_ID + "=" + contact.userInfo.id, null);
}
return result;
}
And the catch statement never got hit.

Related

maven test failing as file modified timings get updated

I have a java project with some test files in the following location:
src\test\resources\data\file\daily
I have some Junit test cases that check and assert based on the file modified time.
FileTime modFileTime = Files.getLastModifiedTime(Paths.get(classPathResource.getFile().getPath()));
when I execute the test cases using intellij without maven, my test passes and the modFileTime has time from the past e.g. 16/04/21 19:48
However, my test cases are failing when I run the tests using maven clean test as the file modified timings in target\test-classes\data\file\daily directory get updated timings.
How can I preserve the original file modified timings? or is there a common solution for this?
The method being called with test:
private boolean isFileAvailable(String file) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(file);
boolean exists = Files.exists(Paths.get(classPathResource.getFile().getPath()));
if (exists) {
FileTime modFileTime = Files.getLastModifiedTime(Paths.get(classPathResource.getFile().getPath()));
long modFileMinutes = modFileTime.to(TimeUnit.MINUTES);
long minutes = FileTime.from(Instant.now()).to(TimeUnit.MINUTES);
return minutes - modFileMinutes >= 5;
} else {
return false;
}
}
mvn clean is getting rid of everything in your target/ directory before running the tests, and repopulating it. Hence, the timestamp will change every run. But this also will be the case for an initial (clean) checkout of the project, which you should be doing before any release build, so ... this is a pretty normal thing to be happening.
However, I agree with all the comments -- your test (not posted) doesn't make a lot of sense. If you want to have your test check a file with a relative timestamp, then e.g. set the timestamp on the file to 4 minutes ago and confirm it's not loaded, then set it to 6 minutes ago and confirm it's loaded. You can set the last-modified value on your test file from within the test. This is much more reliable than relying on something in the test execution system (maven) itself, especially if you generate the test file as part of the test (a good idea)
Also: if you only want to load data files older than a certain time, then I doubt you really want to have those be classpath resources. They should probably be loaded from some other known location. I suspect you are trying to solve some problem with cleverness that would be better solved by something from, e.g., https://commons.apache.org/

Exception: Unmarshalling unknown type code occurred at run time

I am working on Android app and we are working as a team. I am facing a serious issue. And that is when ever I try to get the data from intent it gives me following exception
Parcel android.os.Parcel#355932a: Unmarshalling unknown type code
4784211 at offset 712
I know on SO there are a lot of helping material related to this issue, but my case is different and quiet mind boggling .....
Here is a quick code to see how I am getting my object
try {
if (data.hasExtra("KEY_MY_MODEL")) {
MyCustomModel newSelectedModel = data.getParcelableExtra("KEY_MY_MODEL");
//DO SOME THING WITH OBJECT
}
} catch (Exception e) {
e.printStackTrace();
}
Case1:
I am getting exception on first line if (data.hasExtra("KEY_MY_MODEL")) {
and this is quiet funny because when I inspect the intent object (data) while debugging and if I look into intent object using debugging I can see all my custom object.
The keys of getting object are same, if in any case the key is wrong I think the code inside the if condition must not get run. as it will return false.
But instead of returning false it is giving the above mentioned exception.
Case2: As I told you we are working in team, the same set of code is running perfectly on other system, but when I run app from my system and install app on device, it is giving the exception I mentioned above.
This is very much frustrating. I think there is something wrong with proguard, as I read on S.O but its still not helpful. Any Idea why this is happening? This looks like a big bug.
Note: I am using A.S 3.5 and on other system A.S 3.5 is in use, even we have same set of sdk, configurations and other things are quiet
identical on both sides...
It seems to be a ProGuard issue
Just add this line in proguard.rules.pro/txt
-keepclassmembers class * implements android.os.Parcelable {
static ** CREATOR;
}

TestNg email reports are not current

I have recently converted my project from JUnit5 to TestNG, solely for the purpose of getting decent reports.
I have added a listener that generates the report at the end of each run:
#Override
public void onFinish(ITestContext context) {
System.out.println("FINISH. Sending email report.");
utils.EmailHandler.sendEmail("Finished test", context.toString());
}
My problem is that the reports being sent by email are not from the current run, as desired, but the previous run.
Yet if I open the report in /test-output/custom-report.html using Eclipse IDE it is the correct one!
How do I ensure the emails sent out are current?
I have looked at a couple of similar questions here, but neither are appropriate to me:
Similar questions:
TestNg emailable-report is not updating?
ReportNG HTML report not updating
It finally worked when I moved the call to sendEmail to the end of the GenerateReport method of the listener. That removes all confusion and ensures that that output file is complete before attempting to send it out.
Unless, you 're somehow attaching the old version; from your description, I would say that most likely the file is created AFTER the email is being sent (hence previous version every-time). However, if this theory is correct, it must have emailed an empty file the first time :) Did it?
Idea: insert a couple of minutes delay in your code where the email is being sent. Go check the file as soon as the email leaves the ground, I think it will be the old version (as it hasn't been created yet!)
Have you tried using the #AfterTest annotation? Not sure, but onFinish(ITestContext context) could be lingering somewhere between #AfterMethod and AfterTestcausing your email to leave slightly earlier; before fully attached! Not sure though, why you send an email after each test and not after the whole suite has finished [so to use onFinish(ISuite suite)].
#AfterTest
public void afterTest(ITestContext context) {
//improving answer after initial comments
if(bufferredWriter!=null){
bufferredWriter.close();
}
else{
System.out.println("FINISH. Sending email report.");
utils.EmailHandler.sendEmail("Finished test", context.toString());
}
}
Best of luck!
PS. Nevertheless, I would highly recommend to have a look at extentReports. Definitely better reporting than the built-in that comes with TestNG!

Eclipse debugger "jumps" skipping important code

I have a weird problem debugging an android application.
To be accurate, I copy here the exact code I'm running on:
// Get the puzzles from cache
List<PuzzleDetails> newPuzzles = m_cachedPuzzles.getPuzzles(count);
if(newPuzzles.size() > 0){
// Remove from cache
m_cachedPuzzles.removePuzzles(newPuzzles); // LINE (A)
// Add the new puzzles from cache immediately
m_ownedPuzzles.addPuzzles(newPuzzles);
Log.d("requests", "" + newPuzzles.size() + " moved from cache to user");
}
int left = count - newPuzzles.size();
String deviceId = ResourcesPublisher.getInstance().getDeviceId();
// Don't let anyone else use these points for now
ChallengePointsManagerImpl.getInstance().usePoints(left);
Log.d("requests", "aquirePuzzles(" + left + ")");
// Get a list of requests for 'left' number of puzzles
RequestList reqList = getRequestList(left);
// TODO this is a bug, now
if(reqList.size() > 1){
reqList = getRequestList(left); // LINE (B)
}
When I run on this code, after stepping over the line (A)
m_cachedPuzzles.removePuzzles(newPuzzles);
The debugger "jumps" to the last line (B)
reqList = getRequestList(left);
A simple check shows it really skipped all code between these code lines.
For example the Log.d(...) was never called nor written.
Can anyone give me a clue why does it happen???
Thanks!
Try to do a right click > refresh on the project as it appears on the Project Explorer after you compile the code and before you start debugging.
Perhaps an exception was thrown from line A, and the next step corresponds to it closing off this stack frame?
mIsReaded = (mIsReaded)?false:true;
//mIsReaded = !mIsReaded;
saveReadFlag();
refreshUI();
Toast.makeText(getSherlockActivity(),...
In my case commented codeline cause the similar problem (two lines are skipped). For to solve it I just changed this line by codeline posted above (I mean mIsReaded = (mIsReaded)?false:true;) So different cases haves different solutions. It is result of code optimization by compiler, so please refactor something in (inside)
m_cachedPuzzles.removePuzzles(newPuzzles);
I had the same problem. The thing is, you are probably debugging the code that is in your IDE and not the on on the server. You have to deploy the code from the IDE (Eclypse, Netbeans etc.) on the server. It worked for me! Good luck!
Not directly related to Eclipse but I experienced a similar problem using the Xamarin Extension for Visual Studio and my realization may be of some help. I was developing an App with a Class library. when i made changes to the library then began emulating my App, the DLL wouldn't always rebuild so the debugger would step through the PDB as it was before my latest changes. After rebuilding the DLL, it would step through fine.
In short, rebuild dependencies if there are any changes made.
Hope you solve your issue. Have a good one
comment TODO using multi-line comment
/*// TODO this is a bug, now*/
and try again.

Data in J2ME RecordStore does not persist across sessions

I'm building a mobile app with J2ME, and I've found that the data I write into a RecordStore can be accessed while the program is still running but it is lost after quitting and restarting it. No exception is thrown, the data is simply lost.
UPDATE: Thanks everyone for your suggestions. I'm using NetBeans on Windows 7. I'm not sure if it is using the WTK version I have previously installed or another one it has installed somewhere else. I've checked my WTK folder for the files Pavel wrote about, but couldn't find them. Now I'm testing the features requiring persistence on my phone and everything else in the emulator, but it would of course be much better to be able to test everything in the emulator.
private RecordStore recordStore = null;
public MyMIDlet() {
readStuff(); // output: nothing found in recordStore :(
saveStuff();
readStuff(); // output: stuff
}
private void readStuff() {
try {
recordStore = RecordStore.openRecordStore(REC_STORE, true);
int n = recordStore.getNumRecords();
String stuff;
if (n == 0) {
stuff = "nothing found in recordStore :(";
}
else {
stuff = new String(recordStore.getRecord(1));
}
System.out.println(stuff);
}
catch (Exception e) {
System.out.println("Exception occured in readStuff: " + e.getMessage());
}
finally {
if (recordStore != null) {
try {
recordStore.closeRecordStore();
}
catch (Exception e) {
// ignore
}
}
}
}
private void saveStuff() {
try {
recordStore = RecordStore.openRecordStore(REC_STORE, true);
int n = recordStore.getNumRecords();
byte[] stuff = "stuff".getBytes();
recordStore.addRecord(stuff, 0, stuff.length);
} catch (Exception e) {
System.out.println("Exception occured in saveStuff: " + e.getMessage());
} finally {
if (recordStore != null) {
try {
recordStore.closeRecordStore();
} catch (Exception e) {
// ignore
}
}
}
}
If you use Sun WTK, it creates a file named "in.use" in its "appdb" folder:
C:\WTK25\appdb\DefaultColorPhone\in.use
If you close your emulator in unusual way (kill a process, for example), it would not delete it, and next time you run emulator, it would create temporary folder for storing data:
C:\WTK25\appdb\temp.DefaultColorPhone1
when starting this way, it should print in console: "Running with storage root temp.DefaultColorPhone1".
I fix it, including into my ".bat" file a line for deleting "in.use" file each time, emulator runs. But you should be careful when running several emulators at once.
I experienced the same problem myself, I did however discover that NetBeans, or whatever, deletes the deployed program files after execution. These files are located in the C:\Documents and Settings\MyUser\javame-sdk\3.0\work\0\appdb folder, might be different on Vista/Win7 and I guess the number in the path refers to the emulator you are currently using. Anyways, in this folder look for something that is named like your RecordStore. E.g. "00000002_PSC_onfig.db", which is my suite configuration recordstore named PSConfig. By copying this to e.g. "Copy of 00000002_PSC_onfig.db" it will not be deleted. After NetBeans have cleaned up, just copy it back to its original name.
The next time you hit run in NetBeans your recordstore will be there. It's pain, but at least it gives you the possibility to use the emulator to debug your RMS handling.
This question has been around for a while but I stumbled upon it whilst looking for an answer to the same problem with the emulator but in my case it was when using the Java ME 3 SDK. It is possible that the solution I found might also fix this problem.
Using:
emulator -Xdescriptor:/path/to/app.jad
will according to the docs: "Install a MIDlet, run it, and uninstall it after it finishes."
To persist an installation (and it's data) you should use:
emulator -Xjam:install=<JAD-file-URL>
The JAD file URL can either be a web address or 'file:///path/to/app.jad' if you want to install from your local file system. This installation command will display an application storage number which you can then use to launch the emulator and run the previously installed app by calling:
emulator -Xjam:run=<application-storage-number>
See the docs for further command line options.
I could finally get it to work on a real handset. It seems that, as Martin Clayton suggested, the emulator reset erased the data. I'm still looking for a way to enable persistence in the emulator though.
If you are using windows Vista there can and almost are permission issues. I am not sure how to resolve this but you might want to check that the user that is running the emulator has access to write to the emulator store.
In appdb/$phone/*.db
to fix the storage problem you need to check the option "Storage size" in the netbeans platform manager.
Go in project properties;
go in platform;
manage emulators;
select the sun java wireless toolkit;
go in Tools and Extensions;
open preferences;
storage;
storage size option... set a size.
this works for me
I experienced the same issue on Ubuntu Linux and working with WTK 2.5.2 and Netbeans 8.0.2. I later figured it was caused by shutting down my laptop without closing the emulator. It also happens if you run a second emulator without shutting down the first.
My solution is based on the Best Answer here, just shut down all emulators and delete the file located at
~/j2mewtk/2.5.2/appdb/DefaultColorPhone

Categories