JUnit, where to put my unit test

Hi all,
I have a question regarding unit test.
I am working on a project which has multiple packages. I need to unit test every package using JUnit. One question I have is where to put my unit test. The options are:
1. Write unit test as a separate package. This makes the code clear but only the public functions get tested or I have to make all functions public.
2. Write unit test in the same package of the code to be tested. This makes writing test easier but putting test and code together makes the structure dirty.
Please let me know your opinion and tell me how do you normally do this?
Many thanks,
Regards,
Kevin

It sounds like you're probably a beginner, so this might be overkill, but here goes anyway: You might want to investigate Maven, which defines a standard directory structure that includes a test tree separate from the production tree, but yet still in the same overall folder. The beauty of this design is that you can keep both production & test code together in source control, IDE projects, etc. but they don't interfere with each other.
Even if you don't use Maven now, you might want to consider using their standard directory structure, as it is has stood the test of time, & would facilitate using Maven if you ever decide to in the future.

Similar Messages

  • Unit Test Framework Crashing LabVIEW Project

    [Cross posted to LAVA]
    OS: Windows 7
    LabVIEW 2009, LabVIEW 2009 SP1. 
    Howdy
    If I create a project and add a VI and a unit test to it and save it, then delete the unit test, everything works.
    If I do the above but put the unit test in a virtual folder then delete it, the project hangs and LabVIEW crashes.
    I have tried this on multiple computers and get the same effect.
    If it is an issue I thought this may have been fixed in 2009 SP1, but it is not.
    I do not remember this happening in 8.6.1 but I was using VISTA at the time (if that is related?)
    I get the same problem if I open an existing project with unit tests in it. 
    Additionally I have noticed that the files from the unit test in Windows 7 have no "logo/icon" associated with them. I thought in VISTA they had the same icon as what is shown in the project - the green plus sign (but this was a while ago). 
    Is this a known issue / can anyone else confirm this? 
    Cheers
    -JG 
    Message Edited by jg-code on 04-13-2010 10:02 PM
    Certified LabVIEW Architect * LabVIEW Champion

    Hi Kyle 
    Thank you for your quick reply.
    I am having this problem on my work PC, home PC and a colleague's PC all running Windows 7 and 2009 SP1.
    I have found the problem occurs if I create a new unit test OR drag and drop an existing unit test into the project.
    Attached is a (jing) video of what is happening every time.
    You will see that at the root level of the project (My Computer), I can remove the unit test with no problems at all.
    But if it goes into a virtual folder and I try to remove it - then LabVIEW crashes. 
    The attachment is in LV2009.SP1 and is the sane project as used in the video.
    I look forward to your feedback on resolving this issue I am having.
    Cheers
    -JG 
    Certified LabVIEW Architect * LabVIEW Champion
    Attachments:
    Test Project.zip ‏4 KB

  • Bizunit restriction on Unit Test Adapter

    Hello !
      I'm using Bizunit 4.0 ,which, on its core, seems to use Microsoft testing framework. The tests I'm running are data-driven tests , I'm using a data source and the rows from the data source are parsed one by one , launching thus each test case . What
    I want is to restrict the data source , so only some test cases will be launched .
    In my test scripts , the TestMethod looks like this :              
            [TestMethod]
            [DataSource("ADatabase.ATable")]
            public void runMyTests()
      and the AppConfig : 
    <microsoft.visualstudio.testtools>
        <dataSources>
          <add name="ADatabase.ATable" connectionString="AConnectionString" dataTableName="ATable" dataAccessMethod="Sequential"/>
    I want to restrict the data source to only one row from "ATable"  , for example . I found this but still I can't figure it out where to restrict the Unit test Adapter : 
    After Initializing the Database in TestInitialize, Your Changes Do not Appear
    When the data-driven test runs, Unit Test Adapter connects to your data table and builds a list of data rows. Then for each row it executes the methods TestInitialize, TestMethod, and TestCleanup. If you change data rows in TestInitialize, the Unit Test Adapter
    will not see that change. Therefore, if you want to change your data table for a data driven test, do so in the ClassInitialize or AssemblyInitialize method.
    http://msdn.microsoft.com/en-US/library/ms404700(v=vs.80).aspx
    Thanks !

    After Initializing the Database in TestInitialize, Your Changes Do not Appear
    When the data-driven test runs, Unit Test Adapter connects to your data table and builds a list of data rows. Then for each row it executes the methods TestInitialize, TestMethod, and TestCleanup. If you change data rows in TestInitialize, the Unit Test Adapter
    will not see that change. Therefore, if you want to change your data table for a data driven test, do so in the ClassInitialize or AssemblyInitialize method.
    http://msdn.microsoft.com/en-US/library/ms404700(v=vs.80).aspx
    According to the analysis of this error message, you need change your data table in 
    ClassInitialize
    or
    AssemblyInitialize method.

  • Where should I put my extended unit test assemblies for Visual Studio 2013?

    Hi, I have a question about M/S Unit test extension.
    1. My purpose
    I'm trying to extend Visual Studio Unit Test.
    The points where I extends unit test is to output detail logs.
    My development environment is as follows.
    OS: Windows 8.1Pro (64bit version)
    IDE: Microsoft Visual Studio Professional 2013
      (Version 12.0.30723.00 Update 3)
    2. Things which I'd like to know
    To enable my test extension, it is required to put my test extension assemblies into designated sub folder under Visual Studio's installed folder.
    The source of this information is MS developers blog below.
    (http://blogs.msdn.com/b/vstsqualitytools/archive/2009/09/04/extending-the-visual-studio-unit-test-type-part-1.aspx)
    Q1. It's required to put the assemblies bellow.
    C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies
    Howerver, the guidance in the blog is for Visual Studio 2010.
    In Visual Studio2013, above "PrivateAssemblies" could not be found under "\Microsoft Visual Studio 12.0\Common7\IDE" folder.
    Where should I put my assemblies for my 2013. Is there any substitution for "\PrivateAssembly" folder?
    Q2. Another requirement is to set Assembly information entry into the registry below.
    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\EnterpriseTools\QualityTools\TestTypes\{13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b}\TestTypeExtensions
    For Visual Studio 2013, I could find almost the same node hierarchy, but
    could not find the last "TestTypeExtention" node. Instead,
    I could find "Extensions" node.
    Should I write registry entry here? Or, should I make a new "TestTypeExtension" node and write the entry there?
    Q3.Last question is more basic question.
    Is there any way to kick extended test program in Visual Studio 2013's Test Explore
    without registering my assemblies in the way recommended above.
    I think it's much tender for developer's in debugging phase. For example,
    it is very much helpful, if I could kick a unit test which uses my extended test class in the unit test extension solution.
    That's all. Any information concerning this topics will be appreciated.

    Hi TrailRunner-MF,
    One possible reason is that you didn't view the correct folder, for example, in my windows 8.1 64 bit, it is in the path: "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE", not the "C:\Program Files\Microsoft Visual Studio
    12.0\Common7\IDE " folder.
    Best Regards,
    Jack
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Unit Testing of servlets and jsp by Junit

    hi,
    suggest me how to do the unit testing by junit!
    thanks in advance

    Or abstract the business logic away from the actual servlets themselves (always a good idea) and test those classes outside the context of a servlet framework.
    That limits the code that actually is impacted by being a servlet to the absolute minimum (essentially parameter passing).

  • Unit test with JUnit

    Hi all,
    I use Eclipse IDE: Eclipse Java EE IDE for Web Developers. Version: Indigo Release
    I use JUnit 4. For project properties> Java Build Path> Libraries: I have JUnit4 added. Also under the same tab: Maven Dependencies> I have junit-4.8.2.jar
    In pom.xml I have:
    <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.8.2</version>
          <scope>test</scope>
        </dependency>Basically, I’m writing unit tests using JUnit in the past few months! All I needed to do was to create a test class, add a test method like below:
    @Test
    public void testMethod(){
              // Some test code
    }Right click on method, Run As> JUnit Test
    That’s all I needed to do to either run my unit test or do Debug As> Junit Test to debug my unit test.
    All was fine with the world! Starting yesterday, when I add a new test method in a test class, and then do: Right click on method, Run As> JUnit Test
    Nothing happens! I cannot run or debug any test anymore! Meaning I cannot add any new unit test!
    Let me also add that after I add my test method, I do a clean build thru Eclipse and Eclipse sees the newly complied class which contains my new test method.
    Since none of my configurations changed, I have no idea what went wrong!
    Does anybody has any idea? Any help would be greatly appreciated.

    aksarben wrote:
    Yes, I have an idea: Post your code. I for one am not going to my waste my time speculating and guessing.Could also just be IDE crud. I've had similar problems with older versions of Eclipse. Never with current ones though.
    OP: eclipse creates run/debug configurations for each class. If you search around a little you should find the dialog, I don't know the exact name. I think you can reach it from the "run as" menu options. You should try clearing the settings of your test suite to see if that changes anything.

  • Unit testing in nitrox

    I am new to eclipse and nitrox. Have been building webapps for years with IDEA.
    1) I find info in eclipse help concerning Junit based testing, I find nothing about unit testing in NitroX help. The webapps I am trying to import and build in NitroX must support unit testing. Eclipse Junit based help does not work for me in NitroX webapp.
    2) I have created several types of new webapps in NitroX accepting default parameters in wizard hoping to see how NitroX would lay out a new development environment. None of the results comes close to the development structure described in eclipse help. I find a src folder inside WEB-INF folder. This does not make sense to me and I can find no explanation of what NitroX expects with regards to project structure other than the existence of WEB-INF just below webapp context folder. My ultmate goal is to use both NitorX and IDEA accessing the same CVS repositories. So far I have imported several existing webapps via 'folder import' of source tree, but NitroX does note 'see' my testsrc or testbuild branches and I can not run tests except via my own custom Ant scripts. Any suggetions?
    Thanks

    1) I find info in eclipse help concerning Junit based testing, I find nothing about unit testing in NitroX help. The webapps I am trying to import and build in NitroX must support unit testing. Eclipse Junit based help does not work for me in NitroX webapp.
    If you have a Java class that extends JUnit, then in Eclipse, when you're in the Java-perspective, you can right-click on that class, "Run As..." and select "JUnit Test." That'll give you the JUnit Green or Red bar based on whether the tests succeeded/failed, etc.
    NitroX = Eclipse + Struts functionality. Anything you could do in Eclipse, you can do using NitroX.
    You could, for example, switch to the Java-perspective and perform JUnit testing exactly as in Eclipse without NitroX. Or, if you're in NitroX's "Web" perspective, you can go into Package Explorer and run JUnit tests from there.
    Re: 2)
    NitroX puts a "src" folder in your WEB-INF and sets that to be a source code folder, probably so when the application is deployed on the server, the source code is also on that server (in the isolated-from-the-web WEB-INF directory), which can be beneficial for several reasons, including your development environment and CVS server crashing.
    You could delete that folder, though, and use a folder you created yourself as a source code folder for that project. You'd just have to make sure that when you designate that source code folder (via: right-click on the project -> Properties -> Java Build Path -> Source Folders), you designate the output target of that folder to be /WEB-INF/classes. That'll make sure that, regardless of where your .java files are, your .class files will be placed in the appropriate folder inside your web application structure.
    Regarding NitroX not "see"ing your testsrc or testbuild branches (I assume you mean "folders" instead of "branches" ...), I'm assuming you're using NitroX's "Web" perspective, and looking for those folders in the AppXplorer window. Since your JUnit tests are not a part of the Struts application, you won't find them there -- instead, click over to the Package Explorer view, or switch over to Eclipse's Java Perspective, where everything will behave exactly as you'd expect.
    I hope this helps ..

  • Unit testing in J2EE environment

    Hi All:
    We have been trying to use Junit for creating unit test scripts, and have been bit successful in unit testing DAOs and Value objects - but problem is testing of components like EJBs and Servlets or even classes like Actions or Commands. Since these components run under application server environment, I am not sure how to unit test them without either deploying them on the actual server or simulating app server and rest of the system.
    I was wondering if people could share their experience in writing unit test scripts especially for J2EE components - like Servlets, JSPs and EJBs. On the similar note, is there any similar tool or API for creating integration test scripts?
    Thanks,

    Well - we already have couple of other servers but that's for beta, QA and Integration testing. Problem is with the unit testing. In unit testing, some piece of code is tested by itself. And I am not sure how I can unit test some of the classes like Servlets, EJBs, JSPs or even dependent classes like Commands or Actions. For example, consider following Action class from Java Pet Store:
    public final class CartHTMLAction extends HTMLActionSupport {
    public Event perform(HttpServletRequest request)
    throws HTMLActionException {
    // Extract attributes we will need
    String actionType= (String)request.getParameter("action");
    HttpSession session = request.getSession();
    // get the shopping cart helper
    CartEvent event = null;
    if (actionType == null) return null;
    if (actionType.equals("purchase")) {
    String itemId = request.getParameter("itemId");
    event = new CartEvent(CartEvent.ADD_ITEM, itemId);
    else if (actionType.equals("remove")) {
    String itemId = request.getParameter("itemId");
    event = new CartEvent(CartEvent.DELETE_ITEM, itemId);
    else if (actionType.equals("update")) {
    Map quantities = new HashMap();
    Map parameters = request.getParameterMap();
    for (Iterator it = parameters.keySet().iterator();
    it.hasNext(); ) {
    String name = (String) it.next();
    String value = ((String[]) parameters.get(name))[0];
    final String ITEM_QTY = "itemQuantity_";
    if (name.startsWith(ITEM_QTY)) {
    String itemID = name.substring(ITEM_QTY.length());
    Integer quantity = null;
    try {
    quantity = new Integer(value);
    catch (NumberFormatException nfe) {
    quantity = new Integer(0);
    quantities.put(itemID, quantity);
    event = CartEvent.createUpdateItemEvent(quantities);
    return event;
    In order to unit test above class from say, JUnit test script class, I will have to pass HttpServletRequest object to its method - I will also have to store corresponding command params and store them in the request object - how will you write unit test script for the above class?

  • Suggestions requested for Unit Testing process and build processes.

    Hi All,
    We are using WebLogic WorkShop 8.1 SP2 to build our WebApp. One thing I am trying
    to get together is a "Best Practises" list for aspects of WorkShop developement,
    particularly Unit Testing, Continous Build methodology, source control management
    etc.I have been through the "Best Practises Guide" that comes in WorkShop help,
    but it doesnt address these issues.This could help us all for future projects.
    1)Could anyone give pointers on how to perform Unit Testing using either JUnit/JUnitEE
    in the WorkShop realm, given that Controls cannot be accessed directly from PO
    Test classes.
    2)For a project of size say 5 developers ,does it make sense to have a nightly
    build using tools like CruiseControl?We use CVS for our source control and its
    working out pretty well, but given that we currently have no Unit Tests that can
    be run after the build and that can provide some reports on what broke/what didnt?
    I am sure we all would appreciate any suggestions and more questions on this topic.
    Thanks,
    Vik.

    Hi, Chris,
    can you perhaps explain your solution in greater detail. I am really curious to
    find a way to test controls.
    "Chris Pyrke" <[email protected]> wrote:
    >
    I have written (well it's a bit of a dirty hack really) something that
    lends itself
    to the name ControlTest (it unit tests controls). Its a blend of Junit
    and Cactus
    with some of the source of each brutalised a bit to get things to work
    (not much
    - it was a couple of hours work, when I was supposed to be doing something
    else).
    To write a control test you code something like...
    package com.liffe;
    import com.liffe.controlunit.ControlTestCase;
    import controls.Example;
    public class TestExample extends ControlTestCase
    private Example example = null;
    public void setUp() {
    example = (Example)getControl("example");
    public void testExample() {
    this.assertNotNull(example);
    String result = example.getData();
    assertEquals(result, "Happy as Larry");
    Other tasks required to set up a test are creating a web project with
    a jpf which
    needs some cut and paste code (14 lines) in its begin method and a jsp
    which is
    also cut and paste (5 lines). (ie create a standard web project and paste
    in 2
    pieces of code)
    In the web project you need to create a control (A) with an instance
    name of controlContainer.
    (if it's called something else the pasted in code will need changing
    to reflect)
    In this control you need to put an instance of TestContainerImpl and
    any controls
    that need testing.
    You then need to add a method to the control (A) that looks like…
    * @common:operation
    public String controlTestRun(String theSuiteClassName, boolean xsl)
    container.setControl("example", example);
    return container.controlTestRun(theSuiteClassName, xsl);
    You need to call container.setControl for each control being tested and
    the object
    'container' is the instance name of the TestContainerImpl that was put
    in.
    There are 4 jars (junit, cactus etc) that go in the library. You will
    also need
    the ControlUnitBase project (or maybe just it's jar).
    To use you call a URL like:
    http://localhost:7001/TestWeb/Controller.jpf?test=com.liffe.TestExample
    TestWeb is the name I gave to my web project - this will be different
    for each
    test project
    com.liffe.Example is the class above and will therefore be different
    for each
    test case.
    You can also call
    http://localhost:7001/TestWeb/Controller.jpf?test=com.liffe.TestExample&xsl=true
    (Note the extra &xsl=true) and the browser will (if it can) render it
    more prettily.
    This seems to do the job quite nicely, but there are several caveats
    I would hope
    someone from bea would be able to address before I start using it widely.
    1) To access the control you need to create it (eg as a subcontrol in
    the control
    (A) above.
    To get it into the test case you need to pass it round as an Object (can't
    return
    Control from a control operation). As it's being passed around among
    Java (POJO)
    classes I'm assuming that control remains in the control container context
    so
    this is OK. It seems to work and the Object is some form of proxy as
    any control
    seems to be reproxied before the control is invoked from the test case.
    2) If I'm testing controls called from a JPD then they either need to
    be in a
    control project (and my test cases called from a Web Project) which makes
    for
    a large increase in project numbers (we already have this and are trying
    to resist
    it) To avoid this - as a process project is a brain damaged web project
    I simply
    perform some brain surgery and augment the process project with some
    standard
    files found in any old web project. this means I can call the test JPF
    from a
    browser. This seems nasty, is there a better way?
    3) I would like to be able to deliver without the test code. At the worst
    the
    code can be in place but must be inacessible in a production environment.
    I don't
    know how best to do this - any suggestions (without creating lots of
    projects,
    or lots of manual effort)
    If anyone has read this far I would ask the question does this seem like
    the kind
    of thing that would be useful?
    Hopefully a future version of workshop will have something to enable
    unit testing
    and this hacking will be unnecessary.
    Could someone from BEA tell me if this is a dangerous way to do things?
    Chris
    "vik" <[email protected]> wrote:
    Hi All,
    We are using WebLogic WorkShop 8.1 SP2 to build our WebApp. One thing
    I am trying
    to get together is a "Best Practises" list for aspects of WorkShop developement,
    particularly Unit Testing, Continous Build methodology, source control
    management
    etc.I have been through the "Best Practises Guide" that comes in WorkShop
    help,
    but it doesnt address these issues.This could help us all for future
    projects.
    1)Could anyone give pointers on how to perform Unit Testing using either
    JUnit/JUnitEE
    in the WorkShop realm, given that Controls cannot be accessed directly
    from PO
    Test classes.
    2)For a project of size say 5 developers ,does it make sense to have
    a nightly
    build using tools like CruiseControl?We use CVS for our source control
    and its
    working out pretty well, but given that we currently have no Unit Tests
    that can
    be run after the build and that can provide some reports on what broke/what
    didnt?
    I am sure we all would appreciate any suggestions and more questions
    on this topic.
    Thanks,
    Vik.

  • ABAP Unit Test Problem

    Here we go again on questions regarding ABAPUnit.  We are trying to use Abap unit within a Class object.  All the examples we have seen have to do with Classes and Methods within a Report program. 
    What we have created:
    Class: ZCL_MAIN
    Type: General Class
    Method:  test_abapunit
    Class: ZCL_MAIN_TEST
    Class type: Abap Unit
    Sub Class of ZCL_MAIN
    Method: Test_abapunit_test 
    We try and run the Abap Unit Test from the Test Class and it says it is complete but does not execute our code.  I know we are doing something wrong but are stumped as to what it is.
    Glenn

    Hi Glenn,
    although Uwe and Klaus actually provided for the relevant information we too faced some difficulties at first understanding 'where' you actually put the test classes. So here are the mechanics:
    Open SE80 or SE24 and implement your class ZCL_MAIN.
    While this class is opened, choose <i>Goto->Class-local types->Local Class Definitions/Types</i> from the menu. An editor for local classes is opened on the right.
    Type in your class definition ZCL_MAIN_TEST like this:
    CLASS lcl_main_test DEFINITION FOR TESTING.
      "#AU Risk_Level Harmless
      PRIVATE SECTION.
        CONSTANTS: some_initial_test_value TYPE i VALUE 5.
        DATA: main_class TYPE REF TO zcl_main.
        METHODS setup     FOR TESTING.
        METHODS teardown  FOR TESTING.
        METHODS check_get_my_int FOR TESTING.
        METHODS check_.. FOR TESTING.
    ENDCLASS.
    This is btw a 'normal' local class, no subclass of cl_abap_unit.. whatsoever.
    Go back (menu <i>Goto->Class Definition</i>).
    Choose <i>Goto->Class-local types->local class implementations</i> from the menu.
    Type in your class implementation for ZCL_MAIN_TEST, i.e. implement especially the setup()-method for the test fixture and the various test-methods.
    Compile/activate your class ZCL_MAIN.
    Run the test by choosing <i>Test->Unit Test</i> from the context menu of the class ZCL_MAIN.
    Hope this helps, regards,
    Sebastian

  • Unit Test Validation for Output Ref Cursor Not Working

    Here is the problem:
    I have a stored procedure as follows:
    CREATE OR REPLACE
    PROCEDURE usp_GetEmployee(
    p_employeeId IN NUMBER,
    cv_employee OUT Sys_RefCursor )
    AS
    BEGIN
    OPEN cv_employee FOR SELECT * FROM employees WHERE employee_id=p_employeeid;
    END usp_GetEmployee;
    For this, I am implementing a unit test.
    * In the "Select Parameters" step, I am unchecking the "Test Result" check box for the cursor OUT variable.
    * In the "Specify Validations" step, I am choosing "Boolean Function" and putting the following PL/SQL code:
    DECLARE
    emp_rec {cv_employee$}%rowtype;
    BEGIN
    FETCH {cv_employee$} INTO emp_rec;
    IF {cv_employee$}%FOUND THEN
    RETURN TRUE;
    ELSE
    RETURN FALSE;
    END IF;
    RETURN TRUE;
    END;
    But, when I try to execute this Test, I get the following error:
    Validation Boolean function failed: Unable to convert <oracle.jdbc.driver.OracleResultSetImpl@4f0617> to REF CURSOR.
    If I run in the debug mode, I get the following content in a dialog box:
    The following procedure was run.
    Execution Call
    BEGIN
    "ARCADMIN"."USP_GETEMPLOYEE"(P_EMPLOYEEID=>:1,
    CV_EMPLOYEE=>:2);
    END;
    Bind variables used
    :1 NUMBER IN 1001
    :2 REF CURSOR OUT (null)
    Execution Results
    ERROR
    CV_EMPLOYEE : Expected: [Any value because apply check was cleared], Received: [EMPLOYEE_ID                             COMMISSION_PCT                          SALARY                                 
    1001                                    0.2                                     8400                                   
    Validation Boolean function failed: Unable to convert <oracle.jdbc.driver.OracleResultSetImpl@31dba0> to REF CURSOR.
    Please suggest how to handle this issue.
    Thanks,
    Rahul

    979635 wrote:
    But, when I try to execute this Test, I get the following error:
    Validation Boolean function failed: Unable to convert <oracle.jdbc.driver.OracleResultSetImpl@4f0617> to REF CURSOR.
    If I run in the debug mode, I get the following content in a dialog box:
    The following procedure was run.
    Execution Call
    BEGIN
    "ARCADMIN"."USP_GETEMPLOYEE"(P_EMPLOYEEID=>:1,
    CV_EMPLOYEE=>:2);
    END;
    Bind variables used
    :1 NUMBER IN 1001
    :2 REF CURSOR OUT (null)
    Try explicity declaring the ref cursor instead of using a bind variable, something like (untested)
    begin
      foo sys_refcurosr;
    begin
      test_procedure(foo);
    end;Alternately, in SQL*PLUS use the DEFINE command to ste a named bind variable to type REFCURSOR and use the named bind variable in your test
    Edited by: riedelme on Jan 23, 2013 7:10 AM

  • How to unit test pl/sql collection in the unit test ?

    There is a function SPLIT_LIST (see below) to split a string list to a collection type .
    I'm trying to use the SQLP DEVELOPER to do the unit test on this fucntion. The idea is to use lookups to give multiple string list for different inputs such as 'A,B,C' 'D', '', 'EF,,GH'. for multiple tests a time.
    the expected result (function returns) are SPLIT_TBL('A','B',C'), SPLIT_TBL('D'), SPLIT_TBL(), SPLIT_TBL('EF','','GH')
    But I have problem to use unit test to verify the result based on the lookups as the out put is the collection. anyone has a good idea to do those ?
    create or replace TYPE SPLIT_TBL AS TABLE OF VARCHAR2(32767) ;
    create or replace
    FUNCTION SPLIT_LIST (
    P_LIST VARCHAR2,
    P_DEL VARCHAR2 DEFAULT ' ' )
    RETURN SPLIT_TBL PIPELINED DETERMINISTIC
    IS
    lv_idx PLS_INTEGER;
    lv_list VARCHAR2(32767) := P_LIST;
    lv_value VARCHAR2(32767);
    BEGIN
    LOOP
    lv_idx := instr(lv_list,p_del);
    IF lv_idx > 0 THEN
    PIPE ROW(SUBSTR(lv_list,1,lv_idx-1));
    lv_list := SUBSTR(lv_list,lv_idx+LENGTH(p_del));
    ELSE
    PIPE ROW(lv_list);
    EXIT;
    END IF;
    END LOOP;
    RETURN;
    END;
    /

    I'm having a similar problem - have you solved yours yet?
    As for me, when I return a collection as an output parameter from a procedure, I can't test the result.
    Example: I'm testing a procedure defined like this: Procedure check_this (p_id number, p_result out CompResult)
    where CompResult is defined as: create or replace type CompResult is varray(100) of CompObj;
    Unit Test understands that the data type of out parameter p_result is CompResult.
    It fills in schemaName.CompResult() as the result (empty varray).
    Editing of the result does not appear to be allowed - it's read only.
    So, when the proc returns a varray that isn't empty, the test fails.

  • Trouble w unit test code

    this code compiles fine, but my unit tests starting with the lines
    public static class AllTests extends TestCase {
    are failing with a null pointer exception. i was advised that
    '>
    The testCreateAccount is failing because you're using a local variable,newAccount,
    in the setUp method(), which has the same name as the class instance variable,newAccount.
    Since the testCreateAccount uses the class instance variable, it is null.
    protected void setUp() {
    anAccountServiceImpl = new AccountServiceImpl();
    AccountEntryStruct newAccount = new AccountEntryStruct();'-so i changed all instances of newAccount to newAccount2 in my unit tests (you
    will see towards
    the bottom of my code). it looks like the testCreateAccount method is still
    using a
    null value. i'm not sure if i'm following the advice correctly...
    code is below:
    // AccountServiceImpl.java: The AccountService Implementation
    package com.kafein.accountServices;
    import java.util.Hashtable;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import junit.framework.TestCase;
    import junit.framework.Test;
    import junit.framework.TestSuite;
    import org.omg.PortableServer.*;
    import com.kafein.idl.accountServices.AccountServicePOA;
    import com.kafein.idl.accountServices.AccountEntryStruct;
    import com.kafein.idl.accountServices.AccountStruct;
    import com.kafein.idl.utilities.DateTimeStruct;
    import com.kafein.idl.exceptions.NotFoundException;
    import com.kafein.idl.exceptions.DataValidationException;
    import com.kafein.idl.errorCodes.DataValidationErrorCodes;
    import com.kafein.utils.ServiceHandler;
    import com.kafein.utils.Log;
    public class AccountServiceImpl extends AccountServicePOA {
    POA poa;
    private Hashtable accounts = new Hashtable(); // collection of Accounts
    private static int nextAccountID = 1; // global account ID
    * Construct an instance.
    public AccountServiceImpl(POA aPOA) {
    super();
    poa = aPOA;
    * Overloaded constructor for unit tests.
    protected AccountServiceImpl() {
    poa = null;
    * createAccount is used by administrator to add a new Account
    * in the system.
    * @param newAccount AccountEntryStruct containing data for new account
    * @return int the new unique Account ID
    * @exception com.kafein.idl.exceptions.DataValidationException
    public int createAccount(AccountEntryStruct newAccount) throws
    DataValidationException {
    validateData (newAccount); // throws DataValidationException;
    int accountID = getNextID();
    // Create new Account.
    Account anAccount = new Account(accountID,
    newAccount.userName,
    newAccount.userEmail,
    newAccount.creditCardType,
    newAccount.creditCardNumber,
    newAccount.creditCardExpirationDate.year,
    newAccount.creditCardExpirationDate.month,
    newAccount.userPassword,
    newAccount.initialBalance);
    accounts.put(accountID,anAccount);
    return accountID;
    * isAccountValid is used to validate a user logon.
    * @param accountID AccountID
    * @param userPassword String
    * @return boolean true to indicate an existing Account
    public boolean isValidAccount (int accountID, String userPassword) {
    // Get account with key equal to accountID.
    AccountStruct anAccount;
    try {
    anAccount = (AccountStruct) getAccount (accountID);
    catch (NotFoundException e) {
    return false;
    // Verify password.
    return (anAccount.userPassword.equals(userPassword) ? true : false);
    * getAccount is used to retrieve an existing Account in the system
    * @param int AccountID
    * @return AccountStruct containing data for the existing Account
    * @exception com.kafein.idl.exceptions.NotFoundException
    public AccountStruct getAccount(int accountID)throws
    NotFoundException {
    // Verify that accountID is within an appropriate interval.
    if (accountID < 1 || accountID > accounts.size()) {
    throw new NotFoundException(DataValidationErrorCodes.INVALID_ACCOUNT_ID,
    "Account ID not found");
    // Get Account and convert to AccountStruct (which is returned).
    Account anAccount = (Account) accounts.get(accountID);
    return anAccount.getAccountStruct();
    * getAllAccounts is used to retrieve all existing Accounts in the system
    * @return AccountStruct[] containing all existing Accounts.
    * @fyi returns an empty sequence if no Accounts exist
    public AccountStruct[] getAllAccounts() {
    // Allocate the array of AccountStructs.
    int lastKey = accounts.size();
    AccountStruct[] accountSequence = new AccountStruct[lastKey];
    if (lastKey==0) {
    return accountSequence;
    // DAR:Sort accounts by accountID (int).
    // Create AccountStructs from Accounts.
    for (int i = 1; i <= lastKey; i++) {
    Account anAccount = (Account) accounts.get(i);
    accountSequence[i-1] = anAccount.getAccountStruct();
    return accountSequence;
    * validateData is used to check new account data.
    * @param newAccount AccountEntryStruct containing data for new account
    * @exception com.kafein.idl.exceptions.DataValidationException
    protected void validateData(AccountEntryStruct newAccount) throws
    DataValidationException {
    // Check all of the member data in newAccount.
    if (newAccount.userName.equals("")) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_USER_NAME,
    "User Name must not be empty");
    if (newAccount.userEmail.equals("")) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_USER_EMAIL,
    "User Email must not be empty");
    if (newAccount.creditCardType.equals("")) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_CREDIT_CARD_TYPE,
    "Credit card type must not be empty");
    if (newAccount.creditCardNumber.equals("")) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_CREDIT_CARD_NUMBER,
    "Credit card number must not be empty");
    // Compare creditCardExpirationDate to current date
    // (we only consider year and month).
    GregorianCalendar now = new GregorianCalendar();
    DateTimeStruct proposed = newAccount.creditCardExpirationDate;
    if (proposed.year < now.get (Calendar.YEAR) ||
    (proposed.year == now.get (Calendar.YEAR) &&
    proposed.month < now.get (Calendar.MONTH) + 1)) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_CREDIT_CARD_EXPIRATION_DATE,
    "Credit card has expired");
    if (newAccount.userPassword.equals("")) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_USER_PASSWORD,
    "Password must not be empty");
    else if
    (!newAccount.userPassword.equals(newAccount.userPasswordVerification)) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_USER_PASSWORD,
    "Password verification failure");
    if (newAccount.initialBalance < 0.0F) {
    throw new DataValidationException(
    DataValidationErrorCodes.INVALID_BALANCE,
    "Account Balance cannot have a negative balance");
    * getNextID is used to generate a unique ID.
    * Needs a much better implementation that generates a globally unique ID!
    * @return int an Account ID
    protected synchronized int getNextID() {
    nextAccountID++;
    return nextAccountID - 1;
    * override defaultPOA to return this servant's POA, not Root POA
    public POA defaultPOA() {
    return poa;
    * AllTests is used for unit testing the AccountServiceImpl Class. It
    extends the
    * JUnit testing framework's TestCase class.
    * To execute in graphic mode:
    * java junit.swingui.TestRunner
    com.kafein.accountServices.AccountServiceImpl$AllTests
    * To execute in text mode:
    * java com.kafein.accountServices.AccountServiceImpl$AllTests
    public static class AllTests extends TestCase {
    private AccountServiceImpl anAccountServiceImpl;
    private Hashtable accounts = new Hashtable();
    private Account anAccount;
    private AccountEntryStruct newAccount2;
    public AllTests(String name) {
    super(name);
    protected void setUp() {
    anAccountServiceImpl = new AccountServiceImpl();
    AccountEntryStruct newAccount2 = new AccountEntryStruct();
    newAccount2.userName = "testName";
    newAccount2.userEmail = "test@email";
    newAccount2.creditCardType = "testCreditCardType";
    newAccount2.creditCardNumber = "0123456789";
    newAccount2.creditCardExpirationDate = new DateTimeStruct();
    newAccount2.creditCardExpirationDate.year = 2005;
    newAccount2.creditCardExpirationDate.month = 6;
    newAccount2.creditCardExpirationDate.day = -1; // not applicable data
    newAccount2.creditCardExpirationDate.hour = -1;
    newAccount2.creditCardExpirationDate.minute = -1;
    newAccount2.userPassword = "kafein";
    newAccount2.userPasswordVerification = "kafein";
    newAccount2.initialBalance = 0.0F;
    protected void tearDown() {
    public static void main (String[] args) {
    junit.textui.TestRunner.run(suite());
    public static Test suite() {
    return new TestSuite(AllTests.class);
    public void testGetAllAccountsSizeZero() {
    AccountStruct[] results =
    anAccountServiceImpl.getAllAccounts();
    assertTrue(results != null);
    assertTrue(results.length == 0);
    public void testCreateAccount() {
    try {
    int testAccountID = anAccountServiceImpl.createAccount(newAccount2);
    //fail(); // shouldn't get here
    assertTrue(testAccountID == 1);
    AccountStruct[] results = anAccountServiceImpl.getAllAccounts();
    assertTrue(results[0].userName.equals("testName"));
    assertTrue(anAccountServiceImpl.isValidAccount(1, "kafein"));
    } catch(DataValidationException e) {
    public void testGetAllAccounts() {
    AccountStruct[] results = anAccountServiceImpl.getAllAccounts();
    assertTrue(results[0].userName.equals("testName"));
    public void testIsValidAccount() {
    assertTrue(anAccountServiceImpl.isValidAccount(1, "kafein"));
    }

    thanks again all
    my code now looks like
            public static class AllTests extends TestCase {
              private AccountServiceImpl anAccountServiceImpl;
              private Hashtable accounts = new Hashtable();
              private Account anAccount;
              private AccountEntryStruct newAccount2;
              public AllTests(String name) {
                            super(name);
                    protected void setUp() {
              anAccountServiceImpl = new AccountServiceImpl();
              newAccount2 = new AccountEntryStruct();
              newAccount2.userName = "testName";
                    newAccount2.userEmail = "test@email";
                    newAccount2.creditCardType = "testCreditCardType";
                   newAccount2.creditCardNumber = "0123456789";
                    newAccount2.creditCardExpirationDate = new DateTimeStruct();
                    newAccount2.creditCardExpirationDate.year = 2005;
                    newAccount2.creditCardExpirationDate.month = 6;
                    newAccount2.creditCardExpirationDate.day = -1; // not applicable data
                    newAccount2.creditCardExpirationDate.hour = -1;
                    newAccount2.creditCardExpirationDate.minute = -1;
                    newAccount2.userPassword = "kafein";
                    newAccount2.userPasswordVerification = "kafein";
                    newAccount2.initialBalance = 0.0F;
                    protected void tearDown() {
                    public static void main (String[] args) {
                            junit.textui.TestRunner.run(suite());
                    public static Test suite() {
                            return new TestSuite(AllTests.class);
              public void testGetAllAccountsSizeZero() {
                        AccountStruct[] results = anAccountServiceImpl.getAllAccounts();
                        assertTrue(results != null);
                        assertTrue(results.length == 0);
                    public void testCreateAccount() {
                    try {
              int testAccountID = anAccountServiceImpl.createAccount(newAccount2);
              assertTrue(testAccountID == 1);
              AccountStruct[] results = anAccountServiceImpl.getAllAccounts();
              assertTrue(results[0].userName.equals("testName"));
              assertTrue(anAccountServiceImpl.isValidAccount(1, "kafein"));
                      //fail(); // shouldn't get here
              } catch(DataValidationException e) {
                    public void testGetAllAccounts() {
              AccountStruct[] results = anAccountServiceImpl.getAllAccounts();
              assertTrue(results[0].userName.equals("testName"));
                    public void testIsValidAccount() {
              assertTrue(anAccountServiceImpl.isValidAccount(1, "kafein"));
    }-it compiles cleanly. unit tests testGetAllAccounts() and testIsValidAccount() are failing still, however. i'm not sure how to initialize the struct outside of the setUp method and have the struct be available to methods outside of setUp()

  • ABAP unit: test classes part of prod. code

    Hi all,
    I've read <a href="https://weblogs.sdn.sap.com/pub/u/266">Thomas Weiss</a>'s weblog: <a href="/people/thomas.weiss/blog/2004/12/17/a-spotlight-on-abap-unit-part-1 Spotlight on ABAP Unit Part 1</a>.
    I posted a question there, but apparently Thomas can't answer at the moment, and since I'm impatient for getting someone's opinion, I reckon we can discuss that topic here  :^)
    As explained in the <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/c1be1003-0701-0010-3795-f87160de6483">NetWeaver Developer’s Guide Using ABAP</a>, the test classes are part of the program under test (PUT):
    <i>In ABAP Unit, test classes are part of the production code of the TU. This avoids problems arising from the test code being separate from the production code:
    - Programs and tests must be kept synchronized.
    - You have to ensure that the test and program code are transported together.
    - External test code only enables black box tests with an outside perspective of the tested program.
    Since the test code is part of the production code, it is easy to keep the unit tests and the
    production code up to date if the latter is changed.
    Although the test code and the production code are transported through the system landscape, ABAP unit tests do not increase the load on the production system. By default, the test code is not compiled in the production system. Therefore, the test code can never be executed in the production system.</i>
    On the other hand, this idea is quite different from what suggested by other unit testing frameworks.
    For instance, the documentation of <a href="http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html">Test::Unit - Ruby Unit Testing Framework</a> reads:
    <i>It‘s handy to collect a bunch of related tests, each test represented by a method, into a common test class that knows how to run them.
    The tests will be in a separate class from the code they‘re testing for a couple of reasons. First of all, it allows your code to stay uncluttered with test code, making it easier to maintain. Second, it allows the tests to be stripped out for deployment, since they‘re really there for you, the developer, and your users don‘t need them. Third, and most importantly, it allows you to set up a common test fixture for your tests to run against.</i>
    Regarding the advantages outlined by NetWeaver Developer’s Guide:
    - Programs and tests might be kept synchronized even if they don't belong to the same unit of code.
    - Moreover, you could assure that the test and program code are transported together by saving them in the same package.
    - And quite frankly, I don't have a thourough understanding of the reason why external tests only allow <i>black box tests with an outside perspective</i>.
    What are your opinions on this?
    Regards, Davide

    Hi,
    when I started unit testing with JUnit I was quite surprised that SAP groups the tests with the production code. But now I actually really like it. It has a few advantages:
    - Good tests serve as an excellent documentation so why not bundling them together.
    - If you want to look at the tests they are easy to find.
    - I write all my class tests as local classes. I found out that it really helps me to focus on writing tests only for the class under test. Sometimes it is quite easy to forget the "unit" and write integration tests again.
    Regarding your question:
    >And quite frankly, I don't have a thourough understanding of the reason why external tests only allow black box tests with an outside perspective.
    Usually I would not use the term black box testing in this context. Maybe you mean that it is easy to access private attributes, methods when you group class and testclass together?
    Normally black box testing means that you cannot look at the implementation of the code under test. So your tests are based on the specifications or if there is not one, on your common sense.
    cheers
    Thomas

  • Simulate real servlet container in unit test

    Hi, java experts,
    I have to make unit test of servlet which acted as the same as in real container. The requirements are:
    1. Setup a test servlet container working as real one (e.g. Jboss).
    2. Make multithreaded unit test servlet calls to this test container.
    3. Anyway, simulate everything as the real ones.
    It would be appreciated if you could share your idea. Thank you.

    I haven'y worked with those tools. But I imagine this is where a clean separation between the JSP page and the business logic/database logic will make your simulation easier.
    In summary:
    A JSP page should get all the data it needs to populate itself from the request scope (or session scope). It shouldn't have any business logic or database logic in it (no embedded java scriptlets performing business logic or sql queries). The JSP page shouldn't even instansiate any objects, but instead get them from request scope. The objects should be simple java beans that contain data with get/set methods in them. That way, you can remove the JSP page from yoru tests and simulate data being written to/from some type of mock object instead, using the tools. Not sure this is the correct approach, but it might give you some ideas.
    Also note that Cactus (based on Junit) for example is for testing at one level whereas Junit is for testing at a lower level (individual components in isolation). Looks like your requirement should concentrate at the higher level testing (the devleopers should have used Junit while developing the application. It probably isn't a good idea to apply it after the application is complete at this point since you have limited time).

Maybe you are looking for

  • RMI Client UnmarshalException with UNC paths

    I have a 'none' Java application, that has an embedded JVM which is being used as an RMI server to allow communication to the application from a browser. The applet detects the presence of the RMI server and if not detected, will start the applicatio

  • Problem touch screen IdeaPad U330

    Hi! I know this problem might be posted before, but I couldn't find it.. So I'm trying it this way. Since a few weeks my Lenovo IdeaPad u330 has a problem with the touch screen. When I start my laptop, it works perfectly, but after a few minutes - or

  • How can I get quicktime to work on a PC?

    I have a website with quicktime videos downloaded. They were working last week, and they are still working when I access the site through chrome on a mac.  However, they are not working through chrome, IE, or firefox this week on my pc.  We have upda

  • Java Package PDF

    I look for a JAVA package or a plugin to use to be able to develop an application taking the liberty to visualize the content of a PDF file

  • Linux AppBldr Error 7 Invoke Node

    * LabVIEW 6.02 FDS Linux S/N G12X17332 * AppBldr 6 Linux S/N J12X64523 My SSP subscription on this software has expired. The products were installed on Linux Mandrake 8.2 using the provided National Instruments RPM method. A query of the rpm database