I am trying to write a test to check the method is throwing an IllegalArgumentException. To do that I wrote a simple test code but it gives error. Method is a constructor by the way. public Range(double lower, double upper) {         if (lower &gt; upper) {             String msg = &quot;Range(double, double): require lower (&quot; + lower                  + &quot;) &lt;= upper (&quot; + upper + &quot;).&quot;;             throw new IllegalArgumentException(msg);         }         this.lower = lower;         this.upper = upper;     }  Test code     @Test(expected = IllegalArgumentException.class)     public void testConstructor(){                  new Range(5,-2);              }  What I got is Í java.lang.IllegalArgumentException: Range(double, double): require lower (5.0) &lt;= upper (-2.0). as expected. But why Junit behaves like it is an error, even if I added  @Test(expected = IllegalArgumentException.class) before the test?
8444
How can I use JUnit4 idiomatically to test that some code throws an exception?  While I can certainly do something like this:  @Test public void testFooThrowsIndexOutOfBoundsException() {   boolean thrown = false;    try {     foo.doStuff();   } catch (IndexOutOfBoundsException e) {     thrown = true;   }    assertTrue(thrown); }   I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
37897
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?
18823
Upcasting is allowed in Java, however downcasting gives a compile error.   The compile error can be removed by adding a cast but would anyway break at the runtime.   In this case why Java allows downcasting if it cannot be executed at the runtime? Is there any practical use for this concept?   public class demo {   public static void main(String a[]) {       B b = (B) new A(); // compiles with the cast,                           // but runtime exception - java.lang.ClassCastException   } }  class A {   public void draw() {     System.out.println("1");   }    public void draw1() {     System.out.println("2");   } }  class B extends A {   public void draw() {     System.out.println("3");   }   public void draw2() {     System.out.println("4");   } }
40567
I'm working on a project where i find i'm checking for the following in many, many places:  if(item.Rate == 0 || item.Rate == null) { }   more as a curiousity than anything, what's the best way to check for both cases?  I've added a helper method which is:  public static bool nz(object obj) {     var parsedInt = 0;     var parsed = int.TryParse(obj.ToString(), out parsedInt);     return IsNull(obj) || (parsed &amp;&amp; parsedInt == 0); }   Is there a better way?
79610
an example code what I try to do will surely do better than my english:  public bool IsNumericValueInBounds (string value, Type numericType) {   double d = double.NaN;         bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d });    return inBounds; }   Unfortunately the TryParse method needs an out parameter so this doesn't work. any ideas how to solve this?  (ps.: would'nt this be a nice example for duck typing? - because i know every numericType has an "TryParse" or I am mistaken?)
85121
I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario .
52661
I know there is a difference between assert and verify in Junit; the assert results in a runtime exception, causing test method execution to abort. To overcome this problem, we can have verify which will make test case fail, but allowing test execution to proceed rather than getting aborted.  I doubt there is any such built in approach in testNG. I do understand that best practices say, there should not be multiple asserts in same test case.  But, in practical world, we do come across scenarios where we need to have multiple checkpoints in one test case and we don't want our test method to abort because of one check point failure (test execution should proceed despite failure).  How can we use a soft assert mechanism, similar to verify, which will not abort test method when there is a checkpoint failure.  Example:  @Test(dataProvider = "getMailUrl") public void testMail(email,subject); Assert.assertFalse(subject.isEmpty);//1st checkpoint Assert.assertNotNull(email); //2nd checkpoint Assert.assertEquals(email, "feedback@yoursite.com"); //3rd checkpoint   Now, I want test execution to proceed, even if the 1st checkpoint (validation of subject being not empty) fails. Definitely we will be not be using assert (hard assert). We will need concept of soft assert similar to verify (facilitated by Junit).   I understand, we have to build a customListener implementing TestNG interfaces or extending existing listeners such as TestListenerAdapter. I am still struggling - how can we do this?
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
91490
Possible Duplicate:          When should I create a checked exception, and when should I make a runtime exception?  For example, suppose I created the following class:  public class Account {     private float balance;      /* ... constructor, getter, and other fields and methods */      public void transferTo(Account other, float amount) {         if (amount &gt; balance)             throw new NotEnoughBalanceException();         /* ... */     } }   How should I create my NotEnoughBalanceException? Should it extend Exception or RuntimeException? Or should I just use IllegalArgumentException instead?
11352
Duplicate:     Maybe this is a very silly question but I don't understand why I can't declare two methods that have the same signature when they have different return types.  public class MyClass {     private double d = 0;      public double MyMethod()     {         return d;     }      public string MyMethod()     {         return d.ToString();     } }   I get a compile error that states that the class already defines a member with the same parameter types.  (Obviously the way I'm using this in my code isn't as simple as my example code...but I think it gets the idea across.)  Am I missing something concerning OO design that makes what I'm trying to do an OOP anti-pattern? Surely the compiler should be able to determine which method I'm trying to use as long as I specifically tell it which one I want.  Given MyClass myClass = new MyClass(); I would expect the following code to work:  double d = myClass.MyMethod(); string s = myClass.MyMethod();   I would expect the following code to have problems:  var v = myClass.MyMethod();   But even in the case of var it should result in a compile error.  Can anyone see what I'm doing wrong here? I'm more than happy to be corrected. :-)
31086
I have a generic method defined like this:  public void MyMethod&lt;T&gt;(T myArgument)   The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:  if (myArgument == default(T))   But this doesn't compile because I haven't guaranteed that T will implement the == operator.  So I switched the code to this:  if (myArgument.Equals(default(T)))   Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for.  I can add an explicit null check like this:  if (myArgument == null || myArgument.Equals(default(T)))   Now this feels redundant to me.  ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started.  Is there a better way to solve this problem?  I need to support both references types and value types.
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
105367
I'm trying to develop my first test class in our sandbox instance. When running the below test, I am getting no records return from the first query to build accountsList. The test succeeds, but I have 0% code coverage. The trigger works as expected when ran.  My Test Class:  @isTest private class test_deleteAccountSharesOnUpdate {  static testMethod void updateAccounts()  {     Set&lt;String&gt; accountIds = new Set&lt;String&gt;();      List&lt;Account&gt; accountsList =      [         SELECT Id, Is_Script_Update__c, Description FROM Account     ];      Integer i = 0;     for (Account acct : accountsList)     {         if(i &gt; 199)         {             break;         }          acct.Is_Script_Update__c = True;         acct.Description = 'Testing at ' + System.now();          accountIds.add(acct.Id);          i++;     }      test.startTest();      update accountsList;      test.stopTest();      List&lt;Account&gt; updatedAccts =      [         SELECT Id, Is_Script_Update__c, Description         FROM Account          WHERE Id IN : accountIds     ];      for(Account acct : updatedAccts)     {         System.assertEquals         (             'Testing at',             acct.Description.substring(0,10)         );     } }   }  Trigger I'm trying to test:  trigger deleteAccountSharesOnUpdate on Account (after update)  {    Set&lt;String&gt; accountIds = new Set&lt;String&gt;();  // Gather the account Ids being updated for (Account acct : trigger.new) {     // Only remove shares for accounts being updated by data loader.     // Loader script will insert new shares after this job.     if(acct.Is_Script_Update__c)     {         String terrCode = acct.Territory_Code_String__c;          if(terrCode != null &amp;&amp; terrCode.length() == 5)         {                accountIds.add(acct.id);         }     } }  if(accountIds.size() &gt; 0) {     // Remove the shares associated with these accounts     delete      [         select id          from AccountShare          where RowCause = 'TerritoryManual' AND          AccountId IN : accountIds     ];      // Reset flag that indicates this update is from a data loader.     // Data loader will set this checkbox as true on update.     // This prevents the trigger on UI update.     //     List&lt;Account&gt; accountsList =      [         SELECT Id, Is_Script_Update__c          FROM Account          WHERE Id IN: accountIds     ];      for (Account acct : accountsList)     {         acct.Is_Script_Update__c = False;     }      update accountsList; }   }  Degub log shows no rows returned for the first query:  14:47:14.461 (3461430000)|SOQL_EXECUTE_BEGIN|[8]|Aggregations:0|select Id,       Is_Script_Update__c, Description from Account 14:47:14.483 (3483545000)|SOQL_EXECUTE_END|[8]|Rows:0  Any help is greatly appreciated!
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
86373
Groovy adds the execute method to String to make executing shells fairly easy;  println "ls".execute().text   but if an error happens, then there is no resulting output.  Is there an easy way to get both the standard error and standard out?  (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)  It would be nice to have something like;   def x = shellDo("ls /tmp/NoFile")  println "out: ${x.out} err:${x.err}"
58422
What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?
16584
would report a violation for:  ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;();   The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".  The following line would correct the violation:  List&lt;Object&gt; list = new ArrayList&lt;Object&gt;();   Why should the latter with List be used instead of ArrayList?