Very strange behavior in a unit test. The code is on another computer so I'll shorthand the main aspect of it.
The problem is
When I test as RUN the test checks two objects for 10 properties, it fails saying that the object contains 19 properties.
When I test as DEBUG the test passes for both of the objects where they each have 10 properties.
How the heck is this happening?
#Test
public void testConverterTwoObjects(){
InputStream inFile = this.getClass().getResourceAsStream(TEST_TWO_OBJECTS);
try{
List<MyObject> objs = getConvertedObjects(inFile);
MyObject mob1 = objs.get(0);
MyObject mob2 = objs.get(1);
assertionCheck(mob1);
assertionCheckTwo(mob2);
} catch(Exception e){
// logging
} finally {
try{
inFile.close();
} catch(IOException ioe){
// logging
}
}
}
private void assertionCheck(MyObject t){
assertNotNull(t);
assertEquals(10, t.getPropertyCount());
assertEquals("ALPHA", t.getType());
...
}
private void assertionCheckTwo(MyObject t){
assertNotNull(t);
assertEquals(10, t.getPropertyCount());
assertEquals("BRAVO", t.getType());
...
}
I had a similar problem in PyCharm (Intellij IDEA for Python). After searching hours, it turned out that the garbage collector's behaviour is different in debug mode than in run mode.
Related
I am writing a test automation framework, and trying to simplify life for my users as much as possible. I would like my users to just assert as regular Junit 5 test, and the log writing (my instance of Log4J), report entry (Extent Report) will all be done within the assert.
So, I would like to delegate org.junit.jupiter.api.Assertions class so that:
assertTrue(myCondition, "My Message");
Will do the following (I copied the original assertTrue and added my functionality):
package org.junit.jupiter.api;
#API(status = STABLE, since = "5.0")
public class Assertions {
//...... Some original org.junit.jupiter.api.Assertions functions
public static void assertTrue(boolean condition, String message) {
try{
AssertTrue.assertTrue(condition, message);
}
catch(AssertionError error){
//Do my things - reporter and logger
throw error;
}
}
//...... Some original org.junit.jupiter.api.Assertions functions
}
However
org.junit.jupiter.api.Assertions is a long class to delegate.
it becomes complicated since AssertTrue is only visible in package level.
Would like to get some fresh thoughts on how to resolve it elegantly....
Thanks,
OK,
What I ended up doing was creating a new DelegatingAssert class, and for every Assert I was interested, I created the following:
public static void assertFalse(DelegatingExtentTest testCase, boolean condition, String message) {
try{
Assertions.assertFalse(condition);
testCase.pass(message);
}
catch(AssertionError e) {
testCase.fail("Did not: " + message);
getLogger().error("Fail message: " + e.getMessage());
getLogger().error("Fail stack trace: " + Helper.getStackTrace(e));
throw e;
}
}
I have such problem, as topikstarter here - Using PowerMockito.whenNew() is not getting mocked and original method is called
But I have java 1.4, junit 3.8.1 and jmock 1.2 - and no annotations, of course.
Problem is as it seems in this link - I have a method, which makes new Example(), and then calls Example.someMethod(); I need to get exception from this method to test it. In more wide terms, I need to know how to PowerMockito(or use any other framework) objects in java 1.4 - with junit 3 and without annotations. Make fake object, make any method take this mock object in "new", not create one, and mock it's methods. There is no even method PowerMockito.whenNew() in PowerMockito for junit3...
Any docs, "getting started"s and other things would help - I haven't found anything about PowerMockito for junit3, except of maven dependency link.
public class Example(){
ExampleHelper helper = new ExampleHelper(5);
public void doSmth(){
try{
int i = returnPlus();
System.Out.Println("Nope, we shouldn't come here. We need to visit Catch block");
} catch (myException e){
System.Out.Println("Hoooray, exception!");
}
}
//different package
public class ExampleHelper{
int i;
public ExampleHelper(int i){
this.i = i;
}
public int returnPlus() throws myException{//Yes, method signature tells us, that we are THROWING ecxeption
return i+1;//yes, method DO NOT throws exception
}
}
I'm trying to do something like this, but it doesn't work. In PowerMockito for junit3 there is no such methods - and if I trying to do this with PowerMock+Mockito - there should be annotations, and I have java 4 with no annotations aboard...
public class TestHarderExample extends TestCase {
public void testSomething() {
ExampleHelper exampleHelper = PowerMockito.mock(com.sources.ExampleHelper.class);
Example example = new Example();
try {
PowerMockito.whenNew(ExampleHelper.class).withAnyArguments().thenReturn(exampleHelper);
PowerMockito.when(exampleHelper.giveAplus()).thenThrow(new IOException("Dummy one"));
Example.doSmth();
} catch (IOException e) {
System.out.println("Good one!");
} catch (Exception e){
System.out.println("Bad one...");
}
I am writing a test for already built java class function. I am writing tests using Testng and Mockito and have a Data Provider.
This is my Test
#Test(dataProvider = "myProvider", dataProviderClass = StaticDataProvider.class,
expectedExceptions = SomeException.class)
public void myControllerTest(String argument) throws Exception {
// Mocked object bussiness\
Boolean resultantObject = business.getList(argument);
Assert.assertTrue(resultantObject);
}
This is my Controller which I want to test
public Boolean controller(String argument) {
if(argument != null) {
throw new someException();
} else {
System.out.println("Sucess");
return true;
}
}
This is my Data Providor
#DataProvider(name = "myProvider")
public static Object[][] getDirectoryList() throws Exception {
Object[][] result = null;
// case1 throws SomeException
String testData1 = null;
// case2 don't throw exception
String testData2 = "String";
result = new Object[][] { { testData1 }, { testData2 } };
return result;
}
The problem here I am facing is, I don't want to create another test just to test both buggy and non buggy code and complete my test coverage using a single test case. But when I put Expected Exception on top, it fails on correct code, and when I dont, it fails on buggy code.
NOTE: This is example code and may not work, this is just to take an idea of scenario I am working on and what I am expecting.
Even if you ignore the "one test, one assertion" purist perspective, I think most people agree you should split tests that involve error conditions from tests that prove normal behaviour.
If you want to test multiple error conditions within one test (or if you're really keen on continuing with your plan), you can use this pattern:
try {
// something that should cause an exception
fail("Exception expected");
} catch (ExactlyTheRightException e) {
// ignored
}
I'm trying to test a method for saving to the internal memory on android but All my tests for it are coming up as "Test in error" when I package the app with Maven, when I check the individual test results it says there was a java.lang.NullPointerException in the class, From what I've read it might be something to do with the context that I pass in but I've tried several different methods on generating a context and nothing's worked so far, any advice on how to get these to work would be greatly appreciated. The code for the test:
#RunWith(RobolectricTestRunner.class)
public class SaveSystemTest {
SaveSystem testSS;
Route testRoute;
#Before
public void setup()
{
testRoute = new Route(new LatLng(54.6279022,-5.9146021), new LatLng(54.6279022,-5.9146021),"testRoute");
testSS = new SaveSystem("testSave",Robolectric.application.getApplicationContext());
}
#org.junit.Test
public void saveTest()
{
boolean b = testSS.save(testRoute);
assertTrue(b);
}
The Code for saveSystem.save (Didn't originally have the try catch but I added that trying to get this to work):
public boolean save(Route file)
{
routeList.add(file);
try
{
if(saveToMemory())
return true;
else
return false;
}catch (Exception e)
{
Log.d("SaveSystem", "Exception: " + e);
return false;
}
}
Code for saveSystem.saveToMemory:
private boolean saveToMemory()
{
try
{
FileOutputStream fos = context.getApplicationContext().openFileOutput(saveFileName,Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(routeList);
os.close();
return true;
}catch (Exception e)
{
Log.d("SaveSystem", "Exception: " + e);
return false;
}
}
If you use members in your class which are included via Dependency Injection, you should provide a way to pass in a mocked Object for this context, since they are only injected in runtime of your application and not in your tests.
For a good mocking library, have a look at Mockito.
Stupid mistake, turns out I hadn't initialised the "routeList" List correctly.
Tests should have good coverage of the types of exceptions and errors that this class can throw, and it should have good coverage of the defective statements in the constructor method for CalculatePrimesMother.
The method for which three Junit test case needed is as below:
public CalculatePrimesMother(int numWorkers, int queueLength, int maxPrime,
boolean verbose) {
this.numWorkers = numWorkers;
// Instantiate 3 queues, for thread-safe communication with workers
Candidate = new ArrayBlockingQueue<Integer>(queueLength);
Prime = new ArrayBlockingQueue<Integer>(queueLength);
Composite = new ArrayBlockingQueue<Integer>(queueLength);
this.maxPrime = maxPrime;
this.sqrtMaxPrime = (int) Math.sqrt(maxPrime);
primeFactors = new int[sqrtMaxPrime];
this.verbose = verbose;
}
I tried and created some test case but not able to get full coverage can anyone help me?
public class CalculatePrimesMotherTest extends TestCase {
public CalculatePrimesMotherTest(String name) {
super(name);
}
private CalculatePrimesMother testMother;
#Test
public final void testCalculatePrimesMotherNegativequeueLength() {
try {
testMother = new CalculatePrimesMother(4, -12, 908, false);
} catch (Exception e) {
e.printStackTrace();
}
}
#Test
public final void testCalculatePrimesMotherMinusOne() {
try {
testMother = new CalculatePrimesMother(8, 12, 0, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
What coverage do you get? There are no if tests in your ctor, so a single call should exercise all the code that I see.
You're writing too much code. The setUp and tearDown and test constructor methods are all unnecessary. Remove them.
You don't need the try/catch blocks in the other tests. Remove those, too. You want an exception to trigger a test failure. Catching will hide the error.