Can I test (junit) default case of switch-case statement ?

Hi,
I have a class which has switch-case statements and I am trying to junit test with 100% coverage. My switch-case workes based on enum values.
say my enum values are 1, 2.
switch(getEnumValues) {
case 1:
return "some value";
case 2:
return "some value";
default:
throw new UnsupportedOperationException("No such enum value supported.");
I have test case to test the case 1 and 2 but I am not able to test default case. Can anyone please let me know how can I right a junit test case for default case.
Edited by: TUIJAVADEV on Nov 4, 2008 4:15 PM

yawmark wrote:
TUIJAVADEV wrote:
I have test case to test the case 1 and 2 but I am not able to test default case. Can anyone please let me know how can I right a junit test case for default case.If your enum values are ONE and TWO, and you have cases for both, then there is no "default case". There is nothing to test.
~If I'm reading the OP correctly, they're 1 and 2, not ONE and TWO. That is, not values of a Java enum.
If this is the case, then the easiest way to test the default case is to break the swtich out into a separate, package-accessible method that takes and arg and passes that onto the switch. (There may be variations on this, depending on how your code is structured.)
However, in a similar vein to what the others are saying, if you already know that you'll only ever have 1 and 2 by the time you get to the switch (maybe because the value comes from an argument to the enclosing method, and you've already unit tested that it appropriately throws an IllegalArgumentException when other values are passed, then there's no need to test the default.
Finally, though if it is ints 1 and 2, rather than a true enum, why not switch to an enum?

Similar Messages

  • Switch/Case: How to test byte values in hex format

    OK, this may be a silly question, but being new to Java, I can't seem to get this to work.
    I have a byte value that I want to test in a switch/case statement. The value was assigned to the byte in hexadecimal format. However, testing only works if I use the decimal value of the byte!
    What's even stranger: It does work in a simple if/else statement. In my debugging attempts, I discovered this using the following code:
    //*temporary debug routine
    memoryCells[0] = (byte) 0x86; //LDA
    if(memoryCells[0] == (byte) 0x86)
        System.err.println("byte recognized as hexadecimal!");
    else
        if(memoryCells[0] == -122)
            System.err.println("byte recognized as decimal!"); So, this works in an ordinary if/else statement, but why doesn't it also work in the complex switch/case statement? Snippet below:
           switch (currentOpcode)
                case (byte) 0x86:
                    //*LDA immediate (2 bytes, 2 cycles)
                    registerA = b;
                    currentOpcode = 0x00;
                    cycleCounter = 0;
                break;
            }Thanks in advance for any suggestions...

        public static void main(String[] args) throws Exception {
         byte test = (byte)0x86;
         switch(test)
         case (byte)0x86:
                  System.out.println("Success");
              break;
         default:
                  System.out.println("ooops");
        }This works for me.
    ~Tim

  • SSRS Switch Case Default Value

    Hi 
    I am preparing a chart in my report. My problem is default value of switch statement. I want to hide the default value on my chart. 
    My expression in category group is below. Totally, there are 4 statuses. However, I just use status 1 and status 2.
    Switch(Fields!status.value=1,"New order",Fields!status.value=2,"Order",true,nothing)
    When I execute the report it displays "New order" and "Order" correct. But also displays me default value. I just want these two values. I don't want to display the third one on my chart. How can I hide statuses except 1 and 2 ?  
    KAdir

    Hi KAdir,
    If I understand correctly, you want only display the first and second category values in the chart. In your case, we can use IIF() function to work around the issue.
    Please refer to the following expression in category group:
    =IIF(Fields!status.value=1,"New order",
    IIF(Fields!status.value=2,"Order",Nothing))
    Then, use following expression to replace the Values' expression:
    =IIF(Fields!status.value=1 or Fields!status.value=2,
    Fields!Details.Value,0)
    There is a screenshot for your reference:
    If there are any misunderstanding, please feel free to let me know.
    Regards,
    Alisa Tang
    If you have any feedback on our support, please click
    here.
    Alisa Tang
    TechNet Community Support

  • I would like to know how can i compare a switch case 1 and case 2 in C# is it possible to do that? obs i am a begginer :)

    i would like to know how can i compare a switch case 1 and case 2 in C# is it possible to do that? obs i am a begginer :) I tried to do it with search and sort but it did not go well

    let me give you an example if you add a word case 1( lagg ord) how can i compare that word with case 2 words ( in case 2  already exist 5 words)
    here is the my program 
    using System;
    namespace ConsoleApplication1
        class Program
            static void Main(string[] args)
                //Meny
                Console.WriteLine("\n HÄNGA GUBBE\n");
                Console.WriteLine(" 1) Lägg till ord");
                Console.WriteLine(" 2) Lista alla ord");
                Console.WriteLine(" 3) Spela");
                Console.WriteLine(" 4) Avsluta");
                bool utgång = false;
                do
                    int Valet;
                    Console.Write("\n\tVälj 1-4: \n ");
                    try
                        Valet = int.Parse(Console.ReadLine());
                    catch (Exception)
                        Console.WriteLine("Du skriver fel character!\n" +
                            "\nSkriv bara mellan 1 och 4");
                        continue;
                    switch (Valet)
                        case 1:
                            Console.WriteLine("\n lägg ett till ord! ");
                          var input = Console.ReadLine();
                            break;
                        case 2:
                            Console.WriteLine("\n Lista med alla ord :\n");
                            string[] array = { " Lev", " Skratta", " Gledje", " Gråt", " Njut" };
                            Array.Sort<string>(array);
                            foreach (var c in array)
                                Console.WriteLine(c);
                            Console.WriteLine("\n");
                            break;
                        case 3:
                            string guesses, bokstäver;
                            Console.Write("\n Hur många fel får man ha? ");
                            guesses = (Console.ReadLine());
                            Console.WriteLine(" Utmärkt, då spelar vi!\n");
                            Console.WriteLine(" Felgisningar :" + "0/" + guesses);
                            Console.Write(" Gissade bokstäver ");
                            bokstäver = (Console.ReadLine());
                            Console.WriteLine("Aktuellt ord");
                            Console.Write("Gissa bokstav : " + bokstäver + " \n");
                            break;
                        case 4:
                            Console.WriteLine("\n  HEJ DÅ! \n");
                            Console.Beep();
                            utgång = true;
                            break;
                        //avbryter while loopen, avslutar spelet
                } while (!utgång);

  • How can i subtract two numeric numeric numbers from two switch cases ?

    I have two switch cases in my labView program. I can see them individually on front panel but i need to subtract them and see the result on front panel. 
    Can someone please help me out...
    I am trying to display (Result1 - Result 2) on my front panel. Result1 and Result2 will change with time.
    Regards,
    Awais 
    Attachments:
    play4.vi ‏122 KB

    Move result 1 and result 2 out of the case structures and subract them.
    Right now result 1 or result 2 only get written to if its respective comparison is true.  What do you want to do with the math if either comparison is false?  You haven't defined your problem clearly enough.

  • Usage of Switch Case

    Hi,
    I would like to get some help with regard to usage of Break inside Switch . And moreover can we have a name for switch statements.
    ex : <switch name='xyz'>
    Thanks,
    Jeyanth

    yawmark wrote:
    TUIJAVADEV wrote:
    I have test case to test the case 1 and 2 but I am not able to test default case. Can anyone please let me know how can I right a junit test case for default case.If your enum values are ONE and TWO, and you have cases for both, then there is no "default case". There is nothing to test.
    ~If I'm reading the OP correctly, they're 1 and 2, not ONE and TWO. That is, not values of a Java enum.
    If this is the case, then the easiest way to test the default case is to break the swtich out into a separate, package-accessible method that takes and arg and passes that onto the switch. (There may be variations on this, depending on how your code is structured.)
    However, in a similar vein to what the others are saying, if you already know that you'll only ever have 1 and 2 by the time you get to the switch (maybe because the value comes from an argument to the enclosing method, and you've already unit tested that it appropriately throws an IllegalArgumentException when other values are passed, then there's no need to test the default.
    Finally, though if it is ints 1 and 2, rather than a true enum, why not switch to an enum?

  • How can i test my vpn connection?

    so recently i decided to test if ver 1.3.0.3 of the quickvpn client would work better with the 1.3.0.5 rvs4000 firmware. i loaded quickvpn to an xp pro computer (freshly built, i might add) and got to work. in order to test the connection, i attempted to piggy back off an unsecured wireless network. this network is on the same ISP network as i am.
    i use dynamic DNS, and the unsecured wireless network could resolve my IP correctly, but for some reason i couldnt connect to my home network from the unsecured network. my router is set to respond to lan requests, but i couldnt ping it. my router passes HTTP traffic to a computer in my network, but i couldnt bring up the webpage. finally, my router responds with the router config page over port 443, and i couldnt bring that up.
    so i used my ISP's dialup service to test. initially, as always, i had a million problems with the vpn client. systematically, i tried to resolve the issues. i installed the patch in the readme for quickvpn. i checked log files to see where stuff was failing. eventually, i could connect to the VPN, but would get that "remote gateway is not responding" crap. i know of a (poor) workaround for this which allows you to "finalize" the connection, but that workaround doesnt allow you to ping around in your network. sometime later, after randomly messing with settings, the tunnel would connect without the workaround. i have no idea what "fixed" this.
    despite all this, my 28.8Kbps connection wouldnt allow me to do anything meaningful on my network. i couldnt connect to the router or to a server of mine (http or fileshare). the only thing i could do was ping internal devices. other requests seemed to "hang" rather than timeout or do anything more concrete. basically, i gave up on testing using dialup, even though my router and the client software confirm a good connection. but i still wasnt convinced.
    next, i figured i could create some type of "DMZ" on my network by placing a switch between my ISP's modem and my router. im not a cisco network professional by any means, but im pretty familiar with networking on a above-average level. that said, despite my best, i couldnt get my quickvpn computer to see my router from the "DMZ".
    finally, i figured i could just test the tunnel while directly connected to my network's lan. bad idea. everything seems to go okay until it locks up on "activating policy". rebooting or otherwise ending the negotiation ends in the computer being unable to do anything anymore. when i try to ping anything, i get "negotiating ip security" ad infinitum. the only way i could fix this was by doing a system restore.
    so here's the question: how can i test my quickvpn connection?why can't i just tunnel through my network? and before you scream that you can't, thegreenbow vpn client has NO PROBLEM connecting to my rvs4000 while connected to my own network.

    Hi Aaron,
    I am going exactly the same thing as you however, I had my cousin buy and install a RVS4000 at his house in Australia.
    I access it from the USA so that I can help manage his Local Area Network, he is just not technical..
    I setup a DDNS client on his RVS4000 so that I can always get to his Router via a domain name rather than a IP address.
    I noticed that you didn't mention anything regarding importing client certificate into the directory of the VPN client on your PC.
    I also noticed I disabled IPSec passthrough on the router in Australia, see the pictures below, not sure why, but the VPN client is working.
    I also did not setup any gateway to gateway VPN tunnels, Only added a client , exported certificate as per the manual, See the last screen capture below.
    You will also note if you view the screen captures that my cousins RVS4000 has not been upgraded to the new code.Is there a reason for that...not really...he's just a user, not really technical.  Also note I have not added any VPN tunnels on my RVS4000.
    I have a reasonably reliable connection between the USA and Australia. I didn;t have to play with any other options, just add users to the VPN client database.
    Your description of the working environment of your PC is missing details on the version of XP, so i will mention the following taken from the software release notes of the RVS4000 ;
    There is a known issue with Windows XP SP2 Firewall.
    ICMP packets are always dropped by the firewall when the firewall is enabled.
    This issue causes the QuickVPN client to be unable to establish a tunnel with the remote QuickVPN server successfully.
    Microsoft has released a patch to fix this issue, which you can get from:
    http://support.microsoft.com/kb/889527/en-us
    After you install the patch, the issue should be resolved. You can also fix this issue by upgrading Windows XP to SP3.
    You cannot plug a PC on the same network as the router for testing, they must be on dissimilar WAN  networks for testing purposes.
    Your remote  PC VPN client will not be allocated a IP address in the RVS4000's network, hosts behind the RVS4000 will still respond to pings, as they direct the responses to their default gateway, the RVS4000.
    The thegreenbow VPN client is a distracter at this point costing 50 something EURO  for a license, lets try to get the quickVPN client working !
    So, if you still wish try the following, firstly make sure your XP has been upgraded to  SP3;
    1.  If you upgraded your router to the new version of code, then reset your router to factory defaults to re-initialize your router, yes start again.
    2.  Export the VPN client certificate to the directory that contains the VPN client.  In my case it is;
               "C:\Program Files\Cisco Small Business\QuickVPN Client"
    3.  add a VPN client account to the router
    4.  Use port 60443 from the quickVPN client. and try  VPNing to the router.
    5  hmmm, if the client still fails try disabling IPSec Passthrough on the router for grins and giggles.
    If this fails, call the SBSC at the following location for resolution;
    http://www.cisco.com/en/US/support/tsd_cisco_small_business_support_center_contacts.html
    good luck ...regards Dave

  • Switch/case limit

    I am encountering a very strange problem.. after 39 cases in
    my switch case statement the 40th case does not get executed.. the
    code is in my go button and there are like 1000+ lines of code in
    there.. if I replace my 39th case with the 40th it works but it
    doesn't execute anything after that!! is there a limit on the
    number of case statements we can use in action script??? I am
    really confused with this problem...

    no, but there is a byte limit on a single code block ... I
    can't remember the number off hand. So that's probably what's going
    on there, you might want to consider a looping test or using an
    array.

  • Help with Switch-Case Statement

    How do you get this in a switch-case statement or work with it?
              if (age < 70) {
                        JOptionPane.showMessageDialog(null, "People that are below the 70s are nothing special.");
              else if (age > 69 && age < 80) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 70s are called septuagenarian.");
              else if (age > 79 && age < 90) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 80s are called octogenarian.");
              else if (age > 89 && age < 100) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 90s are called nonagenarian.");
              else (age > 99 && age < 110) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 100s are called centenarian.");
                   }Thanks~

    As per Java Specification, swtich case expects an integer and boolean cannot be used as param for switch.
    In your case switch can be used like this.
    int index = age /10;
    switch(index) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    Your First case
    break;
    case 7:
    your second case
    break;
    case 8:
    third case
    break;
    case 9:
    fourth case
    break;
    default:
    fifth case
    break;
    Take note of the break statements. Its very important. But I wont prefer in this case. Code looks awkward and is not so meaningful.....

  • Switch case

    Hello,
    i was wondering if i can get a value out of a switch?
    something like
    switch(example)
    case 1:
    test=1;
    break;
    case 2:
    test=2
    break;
    switch(example1)
    case 1:
    test1=1;
    break;
    case 2:
    test1=2
    break;
    }so i want for example the sum from the test value from case 2 and the test1 value from case 1 to an messagedialog

    To clear things up lets say...
    int example = 2;
    int total = 0;
    switch(example)
    case 1:
    total = 5;
    break;
    case 2:
    total = 9;
    break;
    Sytem.out.println(total);
    The total will be 9 and if example was 1 then the total would be 5 hence the switch.
    After that I have my own question. How do you do a boolean condition in a case?
    For Example
    switch(example)
    case 1 || 2:
    break;
    case 3 || 4:
    break;
    If I did it the normal way and case1 and case2 had the same code segments it would be pointless to write it twice. Instead using a boolean condition would cut some code in half.

  • Difficulty in using switch-case

    I want to display certain labels on the basis of the value supplied in switch .But it's not working . I don't know how to overcome the problem .Kindly guide me.
    My page is as follows:
    <html>
    <head>
    </head>
    <body>
    <%!
         int i=1;
    %>
    <%
         switch(i)
    %>
    <%
         case 1:
    %>
    In case 1.
    <%
         break;
    %>
    <%
         case 2:
    %>
    In case 2.
    <%
         break;
         default :
    %>
    </body>
    </html>

    The JSP interpreter is putting in statements which makes your code not compile.
    This is caused by the carriage returns in your jsp code.
    switch(i)
    out.print(__constantTable.getString(103)); // *** Syntax: SwitchLabels expected after this token
    case 1:
    out.print(__constantTable.getString(165));
    break;
    out.print(__constantTable.getString(98)); // *** unreachable code
    case 2:
    out.print(__constantTable.getString(166));
    break;
    default :
    }Solution
    1 - Don't mix scriptlets and jsp code in this way. Particularly closing %> and then opening again.
    The following will work
    <%!
    int i=1;
    %>
    <%
    switch(i){
    case 1:
    %>
    In case 1.
    <%
    break;
    case 2:
    %>
    In case 2.
    <%
    break;
    default :
    %>2 - a better solution is to use a custom tag, or tag library like JSTL to implement this
    <c:choose>
      <c:when test="${i == 1}">In Case 1 </c:when>
      <c:when test="${i==2}"> In Case 2 </c:when>
      <c:otherwise> Default value </c:otherwise>
    </c:choose>Cheers,
    evnafets

  • BPEL-Instanz dies silent if switch case is true boolean

    Hello,
    it is very curios. I have the following switch case:
    xp20:compare('string1', 'string2') = 0
    or
    string(xp20:compare('string1', 'string2')) = '0'
    The validation is ok, and the compiler compiles with 0 errors / 0 warnings.
    If I try to invoke the process, the instance dies silent.
    If i write 'string1' = 'string' the behavior is as expected and the instance is running.
    What's the reason
    I am using the last stable release version.
    Best regards
    Harald
    Message was edited by:
    user570114
    Message was edited by:
    user570114

    i just tested your case in 10.1.3.x, it works fine for me. i can see "'two strings do not match" in output variable as expected. can you please copy and past your entire switch block.
    here is my test case ( i took the Switch.bpel sample under references directory):
    <switch>
    <case condition="xp20:compare('string1', 'string2') = 0">
    <assign>
    <copy>
    <from expression="'Value is greater than zero'"/>
    <to variable="output" part="payload" query="/tns:resultMsg/tns:valueResult"/>
    </copy>
    </assign>
    </case>
    <otherwise>
    <assign>
    <copy>
    <from expression="'two strings do not match'"/>
    <to variable="output" part="payload" query="/tns:resultMsg/tns:valueResult"/>
    </copy>
    </assign>
    </otherwise>
    </switch>

  • How can i test if my airport is faulty

    I think my iMac may be faulty my internet it unusually slow at times and i want to runs hardware test to see if my airport is faulty, how can i do this and on lion you cant run the hardware test

    If there is no light on the Expess, then it has most likely passed.
    You could try a Factory Default Reset, just in case.
    Power down the Express for a few minutes
    Then hold in the reset button and keep holding it in while you plug the Express back in to power
    Release the reset button 10-12 seconds after you plug it back in to power
    If you try this a few times and the Express does not respond, then is has failed and will need to be replaced.

  • Map Vs Switch Case

    I am having an Enum where I have two types of implementation to retreive the enum based on input parameter with getJobFrequency() :
    1st implementation of getJobFrequency() with Switch case:
    public enum JobFrequency {
         Daily(1),Weekly(2),Monthly(3), Yearly(4);
         private int value;
         private JobFrequency(intvalue) {
              this.value= value;
         public int getValue(){
              return value;
         public static JobFrequency getJobFrequency(int frequencyId){
              switch(frequencyId){
              case 1:
                   return JobFrequency.Daily;
              case 2:
                   return JobFrequency.Weekly;
              case 3:
                   return JobFrequency.Monthly;
              case 4:
                   return JobFrequency.Yearly;
              default:
                   return null;
    2nd implementation of getJobFrequency() with MAP:
    public enum JobFrequency {
         Daily(1),Weekly(2),Monthly(3), Yearly(4);
         private int value;
    private static final Map<Integer,JobFrequency > lookup
    = new HashMap<Integer,JobFrequency >();
    static {
    for(JobFrequency s : EnumSet.allOf(JobFrequency .class))
    lookup.put(s.getValue(), s);
         private JobFrequency(intvalue) {
              this.value= value;
         public int getValue(){
              return value;
         public static JobFrequency getJobFrequency(int frequencyId){
              return lookup.get(frequencyId);
    Let me know which one is correct to use and why. Thanks a lot for the input

    They are both correct because they both work.
    Any other type of answer for which is "better" depends on the person and the situation. If there are only a few values I'd use the switch statement. If there are lots of values or they can be dynamic, I'd use the map. But I would also dig a little deeper and see if that "frequencyId" cannot be removed and to just use the enum values everywhere.
    BTW: use \ tags to format your code.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How can I change the default  driver to OracleXADataSource in JDeveloper

    Hello,
    How can I change the default oracle driver: oracle.jdbc.OracleDriver to oracle.jdbc.xa.client.OracleXADataSource in JDeveloper Studio Edition Version 11.1.1.0.2, Build JDEVADF_MAIN.BOXER_GENERIC_090328.0229.5205.
    If I modify the file connections.xml from jdeveloper\system\system11.1.1.0.31.52.05\o.jdevimpl.rescat2\connections in the sense that I change the driver class, then in JDeveloper when I test my connection I have this problem: Test failed: oracle.jdbc.xa.client.OracleXADataSource cannot be cast to java.sql.Driver
    Why do I need this XA version of the oracle driver? Well I tried, from a book to reproduce the model of an application: entities, stateless and stateful session beans, mdb, web services and a client to test one part of the model.
    And because of the JMS server I need an XA driver.
    I deployed to the integrated wls 10.3 and when I test my client, if I use the default driver for the connection the an error message appears tell me either to emulate two-phase commit or to use XA driver.
    My application works very well, if I configured in the console of the integrated wls 10.3 a datasource with the same name as my ide/application connection that has for the Driver Class Name: oracle.jdbc.xa.client.OracleXADataSource in the Connection Pool tab.
    Thank you.

    Open DIsk Utility and in the toolbar select Disk Image. The file selector will open and you'll have to do three things: 1) just as with any file, name it and point the file selector to where you want it to be saved, 2) near the bottom you'll see name - type iWork 2013 and 3) below that select the image size. Click on size, choose custom and type 1500 MB then click on the Create button.
    Some time will pass and then you'll see an external disk pop up on your desktop and/or the Finder window sidebar. Drag the three programs into it and eject it like any other external disk. Now delete the programs from your applications window.
    Where ever it was you pointed the file selector to you'll see the file you created. Double click on it and the disk image will mount again.

Maybe you are looking for

  • A List of Issues and Problems in CS3

    I've been logging concerns I have with CS3 over the course of a few edit sessions. I'll list them and see if anyone has any solutions or ways to make these quarks a little more tolerable. (I'm coming from Pro 1.5 into CS3) My Current Configuration: D

  • Am method and popup

    When I drag and drop a AM method in a main (non popup) page as a ADF BUTTON it works fine. But when I drag and drop the same AM method in a popup page as a ADF BUTTON it does not work. Any idea why please?

  • Raw files in iphoto 09

    When I drag a photo from iphoto to the desk top, the file info changes from a nef file to a jpg file. My OS is 10.5.8 and am using iphoto 09. My camera is a Nikon E 8800 (CoolPix). The reason I drag the file from iphoto to the desk top is that I want

  • HELP QUICK, iMac blurry in verticle lines, lines in loading screen, loading screen yellow.

    Hey all, i have a problem with my mid 2010 iMac, i have weird lines that appear on the loading screen and the apple logo looks distorted. the loading screen takes a longer time to load and when it finally does there are vertical strips that appear on

  • (and happy new year!)

    I get abit sick and tired of he fact that they just random delete al kinda playersWhen you report a real bad player then nothing happens but players who never say something wrong even did buy gold get deleted without reasonAnd then they get a logo li