Unit testing: Mocking custom classes with null

Hi,
I was trying to save time on testing the usual hashCode() and equals() methods so I got this class: http://www.cornetdesign.com/files/BeanTestCase.java.txt
I altered it a bit as it wasn't handling standard classes only primitives.
Anyway, I got to the point to include my own custom classes.
I have to create a 'mock' object for my class properties, e.g. field.getType().newInstance()
Fine, but there are some tricky instances. E.g. when I'd like to create an instance of java.net.URL which takes a URL as String in the constructor.
This is almost impossible to automate as it has to be a valid URL format not just a random String.
So, I thought I set them to null, e.g.
assertTrue(o1.equals(o2))
as both properties are null.
Is this the right approach you think?
I welcome any suggestions.
My initial idea was to save enormous amount of time automating the hashCode() and equals() method tests as they took so long to write.
Thanks

Trouble would be that you are only testing the null branch of the equals or hashCode, which typically have to check for null, then if not null do an actual comparison.
It's worth the effort of learning to use a package such as EasyMock to create and program mock objects. It's tidiier if you are progamming to interfaces, however, but it will mock ordinary objects, though probably not if they are final.
What you could do is to define a factory interface, and have a table of anonymous classes wich generate various types. In effect create a library of dumy object factories.
Something like:
private interface DummyGenerator {
      Object generate(int idx);
      Class<?> getType();
private final static DummyGenerator[] generatorsTable {
    new DummyGenerator() {
           public Object generate(int idx) {
             return new URL("http://nowhere.com/" + idx);
     public Class<?> getType() { return URL.class; }
.. generators for other classes
private final static Map<Class<?>, DummyGenerator> genMap = new HashMap<Class<?>, DummyGenerator>(generatiorsTable.length);
static {
    for(DummyGenerator gen : generatorsTable)
        genMap.put(gen.getType(), gen);
}

Similar Messages

  • Unit test runs perfectly fine with NUnit but fails when run from TestExplorer

    Hello all,
    I have a TestProject, Harmony.Tests. In there, I have a method AddApplicationEvent()
    which calls another method Send(InvokeRequestMessage requestMessage) which calls a webservice (OperationHandlerBrokerWebService). 
    The code snippet looks like this. This is not the complete code but a part where we are calling the web service. It fails on the underlined Italic line of code.
    OperationHandlerBrokerWebService brokerService = new OperationHandlerBrokerWebService();
    brokerService.UseDefaultCredentials = true;
    brokerService.Url = address;
    brokerService.Timeout = timeoutInMilliseconds;
    byte[] serializedResponseMessage = brokerService.InvokeOperationHandler(serializedRequestMessage);
    The same test works and passed fine when I ran it with NUnit, but failed with following exception when I tried to run it from TestExplorer. 
    Test Name: AddApplicationEvent
    Test FullName: N4S.Harmony.Tests.CaseManagement.HarmonyFacadeTests.AddApplicationEvent
    Test Source: d:\TFS\TMW\Dev\TMWOnline\Harmony\N4S.Harmony.Tests\CaseManagement\HarmonyFacadeTests.cs : line 665
    Test Outcome: Failed
    Test Duration: 0:00:00.296
    Result Message:
    SetUp : Message returned System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Invalid token for impersonation - it cannot be duplicated.
    at System.Security.Principal.WindowsIdentity.CreateFromToken(IntPtr userToken)
    at System.Security.Principal.WindowsIdentity..ctor(SerializationInfo info)
    at System.Security.Principal.WindowsIdentity..ctor(SerializationInfo info, StreamingContext context)
    --- End of inner exception stack trace ---
    at System.RuntimeMethodHandle._SerializationInvoke(Object target, SignatureStruct& declaringTypeSig, SerializationInfo info, StreamingContext context)
    at System.Reflection.RuntimeConstructorInfo.SerializationInvoke(Object target, SerializationInfo info, StreamingContext context)
    at System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context)
    at System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder)
    at System.Runtime.Serialization.ObjectManager.DoFixups()
    at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
    at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
    at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
    at N4S.Forms.OperationHandlerBroker.AMessage.DeserializeMessage(Byte[] serializedMessage)
    at N4S.Forms.OperationHandlerBroker.WebServiceServer.BrokerService.InvokeOperationHandler(Byte[] serializedInvokeRequestMessage)
    --- End of inner exception stack trace ---
    expected: <0>
    but was: <1>
    Result StackTrace:
    at N4S.Harmony.Tests.TestHelper.InvokeOperation(OperationHandler handler, OperationHandlerInput input, Boolean expectedToWork) in d:\TFS\TMW\Dev\TMWOnline\Harmony\N4S.Harmony.Tests\TestHelper.cs:line 136
    at N4S.Harmony.Tests.TestHelper.LoginAsUser(String username, String password) in d:\TFS\TMW\Dev\TMWOnline\Harmony\N4S.Harmony.Tests\TestHelper.cs:line 394
    at N4S.Harmony.Tests.TestHelper.Login(TestUserName requestedUser) in d:\TFS\TMW\Dev\TMWOnline\Harmony\N4S.Harmony.Tests\TestHelper.cs:line 377
    at N4S.Harmony.Tests.TestHelper.LoginAsAdvisor() in d:\TFS\TMW\Dev\TMWOnline\Harmony\N4S.Harmony.Tests\TestHelper.cs:line 230
    at N4S.Harmony.Tests.CaseManagement.HarmonyFacadeTests.Login() in d:\TFS\TMW\Dev\TMWOnline\Harmony\N4S.Harmony.Tests\CaseManagement\HarmonyFacadeTests.cs:line 76
    at N4S.Harmony.Tests.CaseManagement.HarmonyFacadeTests.SetupTest() in d:\TFS\TMW\Dev\TMWOnline\Harmony\N4S.Harmony.Tests\CaseManagement\HarmonyFacadeTests.cs:line 67
    I am not sure what causing the issue. I checked the Credentials, Windows Identity during both the test run and there is no difference. Please advise !!
    Thanks,
    Deepak

    Hi Tina,
    Thanks for your reply. 
    I do have NUnit adapter installed. I even noticed that the test runs fine with NUnit GUI and also if I run it through Resharper Test Explorer window. 
    As you can see in the image above the same test is passed when I ran it from Resharper Unit Test Explorer window but fails when I ran it from Test Explorer window. I also captured the information on fiddler. 
    There was a significant difference in the Header Content length. Also under the User-Agent property the protocol versions are different. 
    Not sure why VSTest ExecutionEngine is picking a different version.
    The UnitTest in question is calling a webservice method which in turn calls a method from another referenced project. 
    Web Service class
    using System;
    using System.Web.Services;
    using N4S.Forms.OperationHandlerBroker.Server;
    using NLog;
    namespace N4S.Forms.OperationHandlerBroker.WebServiceServer
    /// <summary>
    /// The operaton-handler broker service.
    /// </summary>
    [WebService(Description = "The N4S Forms Operation-Handler Broker Web-Service.", Name = "OperationHandlerBrokerWebService",
    Namespace = "N4S.Forms.OperationHandlerBroker.WebServiceServer")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class BrokerService : WebService
    { /// <summary>
    /// Calls <see cref="HandleRequest"/>. Updates performance-counters.
    /// </summary>
    /// <param name="serializedInvokeRequestMessage">the binary-serialized <see cref="InvokeRequestMessage"/></param>
    /// <returns>the binary-serialized response message</returns>
    [WebMethod(BufferResponse = true, CacheDuration = 0, Description = "Invokes the requested operation-handler and returns a binary-serialized response-message.", EnableSession = false)]
    public byte[] InvokeOperationHandler(byte[] serializedInvokeRequestMessage)
    logger.Trace(Strings.TraceMethodEntered);
    PerformanceMonitor.RecordRequestStarted();
    InvokeRequestMessage requestMessage = (InvokeRequestMessage) AMessage.DeserializeMessage(serializedInvokeRequestMessage);
    InvokeResponseMessage responseMessage;
    try
    responseMessage = HandleRequest(requestMessage);
    PerformanceMonitor.RecordSuccessfulRequest();
    catch (Exception)
    PerformanceMonitor.RecordFailedRequest();
    throw;
    finally
    PerformanceMonitor.RecordRequestEnded();
    logger.Trace(Strings.TraceMethodExiting);
    return AMessage.SerializeMessage(responseMessage);
    UnitTest snippet
    OperationHandlerBrokerWebService brokerService = new OperationHandlerBrokerWebService();
    brokerService.UseDefaultCredentials = true;
    byte[] serializedResponseMessage = brokerService.InvokeOperationHandler(serializedRequestMessage);
    Please advise.
    Thanks,
    Deepak

  • How can I write unit tests for BizTalk Maps with multipe inputs?

    I want to bring all my maps under unit test coverage, but can't seem to find a way to test maps with multiple inputs. Maps with multiple inputs are first merged into a single schema by biztalk and then the map actually uses that inline schema as source.
    What I tried is- produced a generated instance of source schema by clicking "Test Map", and then modified the skeletal instance by stitching together the multiple input files into it. There are two problems I am facing going forward that way- 1#
    It takes a lot of time to craft a mock input of inline schema and 2# the mock input fails input validation although the input works just fine in the orchestration.
    So is there a better or standard way to test such Maps?

    For testing maps with multiple inputs, follow the below steps-
    Lets assume you have a map with two input schemas A and B and output as C.
    1) To create the required schema just reverse the inputs i.e. make a map with C as input and A & B as output. Later do a test map. This will generate an XML File with schemas A & B. 
    2) Now you just to need to replace OutputMessagePart_0 to InputMessagePart_0
    and OutputMessagePart_1 to InputMessagePart_1
    Later you can use this xml for testing your original map.
    Refer the below article
    Developing and Testing Maps which have Multiple Source and Destination Schemas
    Thanks,
    Prashant
    Please mark this post accordingly if it answers your query or is helpful.

  • WebServiceContext is null in Unit Tests

    I'm trying to write Unit Tests for a service which defines a webservice context thus :
    @Resource protected WebServiceContext wsContext = null;
    public void foo() {
          messageContext = wsContext.getMessageContext();
          List<Header> headerList = (List<Header>) messageContext.get(Header.HEADER_LIST);
    }This works fine on the Server (Websphere). However, calling the same in a Unit Test fails as wsContext is null.I'm using Spring as the backbone for the entire service framework. I checked the spring configuration for this bean and nowhere does it declare a wsContext as a property setter. It seems to just work when deployed on the AppServer!
    However, the same injection fails to happen while running Unit Tests. I'm trying to figure out if there is a way I can stub it out, to no avail. Any help would be appreciated!
    Jim
    Edited by: Titan1978 on Jul 20, 2010 6:45 AM

    I found that I was not receiving a null on the WebServiceContext. My problem was that I was trying to use it in the class constructor, but it is not available there.
    The following:
    MessageContext ctxt = wsc.getMessageContext();
    ServletContext req = (ServletContext) ctxt.get(ctxt.SERVLET_CONTEXT);
    works fine when used in a web service method.
    My second issue was with getInitParameter() method. To use getInitParameter(), the elements must by defined in the context-param section of the web.xml, not in the init-param.
    Bruce.

  • A Custom Class says my class is Null

    Hi,
    I have a class (Math2) with misc functions for my project. It
    has a function called CheckRelations() which basically checks a
    static array in another class (relation). But the Math2 class acts
    as if the Relation class is non-existent, even though I have
    imported it and I also have all files in the same folder. When I
    try to relate to the class in any way i get a Runtime-Error 1009
    (Cannot access a property or method of a null object reference.)
    I tried tracing the class along with two other classes (one
    imported, but another is not) the two classes trace fine: [class
    Human] [class relationship]. The Relation class when traced in the
    Math2 class results in a 'null'
    Code for the CheckRelations function in math2 class: (takes
    in String value, and returns the index at which the input =
    relation.Type ( i.e. if (String_Input == Relation.Relations
    .Type) --> return i ) Return -1 if not found)
    import Human;
    import Relation; //notice that Relationship is not imported
    yet traces out fine
    //......REST OF CLASS (other static functions
    public static function
    CheckRelations(relationType:String):int {
    ///////Variables
    trace(Human,Relation,Relationship); //Human and Relationship
    are classes I used to test problem
    //Output: [class Human] null [class Relationship]
    var relationType:String;
    //relationType: the relation to look for in the relations
    array
    var array:Array = Relation.Relations; //Relations is a
    public static var (array)
    //array: the array to look inside
    var relation:Relation;
    //relation: used to hold temp values of relations to compare
    var ReturnValue:int = -1;
    //ReturnValue: the value to return
    var i:uint;
    //i: used in for..loops
    ///////Function
    //SOURCE OF ERROR: any reference to Relation class
    RelationCheck:for (i = 0; i < array.length; i++) {
    relation = array as Relation;
    if (relation.Type == relationType) { //relation.Type is a
    string value
    ReturnValue = i;
    break RelationCheck;
    return ReturnValue;
    Code for getRelation function in Relation class:
    public static function getRelation(relation:String):Relation
    var val:int = Math2.CheckRelations(relation); // SOURCE OF
    ERROR
    if (val == -1) {
    GameError.InvalidRelation(relation); //throws error when an
    invalid relation is specified {this is NOT the problem I'm having}
    }return Relations[relation];
    ------------------------------------------------------------------------------------------ ---------------------------------------------------------

    OK, I believe I have got the problem. When I tried to call
    the Relation class from another class, I couldn't do that before I
    cut any references to the Math2 class. So i ported the
    checkRelations function into the Relation class itself in order to
    cut any reference to the Math2 class. But to my surprise, when I
    did that, I could trace out the Relation class normally from not
    only another class, but the Math2 class itself! So after a long
    time fiddling with the program I figured out that the reason Math2
    was unable to relate to the Relation class was because the Relation
    class was still not fully initiated. And since Relation class used
    the Math2 class as part of the initiation, and the Math2 class
    needed to use the Relation class itself in order to initiate the
    Relation class there was practically no existence of the Relation
    class as it was still in the initialization process (if that makes
    any sense). So instead i called the defineRelations function in my
    main fla file, to make sure the Relation class is all set before
    hand, and it worked like a charm.
    Anyways, thanks a lot Jamesabth
    for taking the time to look at my code and help me
    out, it was your advice that lead me to this discovery after all .
    And also thanks to anyone who has took the time to look through my
    problem even though they may have not been able to help me with
    it.

  • How to make set up with first call of method of a custom class?

    Hello
    I have build a custom class with a few custom methods.
    Method1 is called per every record of internal table. I need to set up certain parameters tha are the sme for all the calls  (populate the range , to fill the internal table , etc). This should be done only once.
    call method ZBW_CUSTOM_FUNCTIONS=>METHOD1
            exporting
              I = parameter1
            importing
              O = parameter2.
    Loop at ....
       <itab>-record1 = parameter2
    endloop.
    Methods2, 3 , 4 dont need any set up.
    Can somebody tell me how to do it within class?
    Thanks

    Instance methods (as opposed to static methods) are called on an object, which is an instance of a class. Broadly, think of the class as a template for the creation of objects. The objects created from the class take the same form as the class, but have their own state -- their own attribute values. In pseudo-ABAP (this won't even close to compile), let's say you have the following class:
    CLASS cl_class.
         STATICS static_attr TYPE string.
         DATA attr1 TYPE string.
         DATA attr2 TYPE i.
         CLASS-METHOD set_static_attr
              IMPORTING static_attr TYPE string.
              cl_class=>static_attr = static_attr.
         ENDMETHOD.
         METHOD constructor
              IMPORTING attr1 TYPE string
                                 attr2 TYPE i.
              me->attr1 = attr1.
              me->attr2 = attr2.
         ENDMETHOD.
         METHOD get_attr1
              RETURNING attr1 TYPE string.
              attr1 = me->attr1.
         ENDMETHOD.
    ENDCLASS.
    When you create an instance of the class (with CREATE OBJECT oref), the constructor is implicitly called. You can pass parameters to the constructor using: CREATE OBJECT oref EXPORTING attr1 = 'MyString' attr2 = 4.
    You then call methods on the instance you have created. So, oref-&gt;get_attr1( ) would return 'MyString'.
    The constructor is called when the object is created (so, when you call CREATE OBJECT). At this time, the setup is done, and any subsequent methods you call on the object will be able to use the attributes you set up in the constructor. Every object has its own state. If you had another object, oref2, changing its instance attribute values would not affect the values of oref.
    Static methods and attributes are different. A static attribute exists only once for all instances of the class -- they share a single value (within an internal session, I think. I'm not sure of the scope off-hand.) You also call static methods on the class itself, not on instances of it, using a different selector (=&gt; instead of -&gt;). So, if you called cl_class=&gt;set_static_attr( static_attr = 'Static string' ), 'Static string' would be the value of static_attr, which belongs to the class cl_class, and not instances of it. (You can also set up a class constructor, which is called when the class is loaded, but that's another subject.)
    To answer your question more succinctly: no, the constructor is not called before each method. It is only called when you create the object. Any subsequent methods called on the object can then access its attributes.
    Please have a look at [http://help.sap.com/saphelp_nw70ehp2/helpdata/en/48/ad3779b33a11d194f00000e8353423/frameset.htm] for a more thorough treatment of basic object concepts. (The rest of that documentation is very thin, but it'll get you started. Also, it doesn't appear to deal with statics. You'll have to look elsewhere for that.)

  • 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()

  • TDD: Using Test-Data Containers(eCATT) in Unit-test

    Recently I learned about TDD, and learn how to write unit-test for some class. But When I write a report(with DB, post account doc) , I come across some problem.
    1. I  have some method just select some data form table , but I don't know how to write this unit-test? I know I can create a TDC though eCATT, but my method is select form table ,how do I finish this ?
    2. Also I have some method just handle data, such as check the data or move to another internal table, do I need to write unit-test for this kind method?
    Further more , I search the SCN many times , I didn't find a suitable program as TDD program (include SQL, input , output, data handle ). Is there anyone can share your example in TDD for us , thank you so much.
    Best Regards!

    Glad that you have interest in TDD. I write on ABAP unit at my site zevolving.com 
    TDD should not dependent on the data selection from the DB as the DB data could be changed and your test would fail without you being changing the logic.
    To avoid the dependency on the data, you need to prepare the dummy test data. You need to than also prepare the expected output from the dummy test data. Once you have the dummy test data, you can pass the data to the method (or subroutine or FM) and get the actual output. You compare the expected output with the actual output to verify it works as expected.
    For your example, you should modularize the program - method for GET_DATA, method for PREPARE_OUTPUT, method for GENERATE_OUTPUT. From these methods, you should be able to write unit test on PREPARE_OUTPUT.
    In your unit test, you need to declare local variables in your test class if you use the subroutine. if you use the class and methods, you can instantiate the object and you get all the variable access. Thats the reason it would be more easier and less confusing when using the objects with unit test.
    Fill up these tables. Say LT_VBRK, LT_VBFA, LT_VBAK. Make sure your subroutine PREPARE_OUTPUT has importing parameters. Pass these to them. Also, prepare the LT_OUTPUT_EXP with the expected results. Declare the table which would hold the actual values LT_OUTPUT_ACT and receive the results from the subroutine PREPARE_OUTPUT. Use the method  cl_aunit_assert=>assert_equals to check the values in the LT_OUTPUT_EXP and LT_OUTPUT_ACT.
    Regards,
    Naimesh Patel

  • Pending Class onResult in custom class.

    Ok,
    I have a custom class with private field:
    private var test:Stringint the constructor I load the web
    service:
    pws = new WebService(Constants.getWsURL() + "?WSDL");
    then I call a method on the WS:
    var pcLoadModel = pws.LoadModel();
    pcLoadModel.onResult = pcLoadModel_Succ;
    pcLoadModel.onFault = pcLoadModel_Fail;
    where:
    public function pcLoadModel_Succ(result){
    //some code.
    The problem is that where it says "some code", I cant access
    the members of my class! Why not? in the debugger I clearly see
    that I have left the scope of the instance of the class I was
    working from. I dont understand why this happens.
    Anyone has an answer to this?
    Thanks you :)
    Jp

    i'm not quite following - are you saying you want to access
    panelDiagram in functions other than your addDiagram function? just
    take your variable definition out of your function and make it a
    class variable eg put the following line above your constructor:
    private var panelDiagram:*;
    and in the second line of your addDiagram function use:
    panelDiagram = new diagramClass();
    sorry if this isn't your answer, if it isn't i'm struggling
    to understand the problem.

  • Can we get  reference of WD component in custom class of enhanced View cont

    Dear Member,
    We are enhancing WD component. We need to get a reference of WD component in custom class of enhanced View controller (post exit) so that popups can be triggered or URLs can be called?. How should we get reference of WD component? I need to know cons of our approach.
    ...Naddy

    Hi,
    Create one static attribute in your custom class with type ref to of your component and populate this attribute in webdynpro enhancement and then use this reference in your custom class.
    Regards,
    Pon Murugesh

  • Using custom classes that are not beans

    Hi folks,
    Is it possible to use java classes that are not beans. I mean, on a page, could you say Customer cust = new Customer("Jones", 25);
    if you had a Customer class with a constructor that took a name and age (String and int).
    If so, how do you go about this- do you need to import the class, or put it in a standard location? I'm using Tomcat, and would guess that this would go in WEB-INF/classes?
    I hope it's not a stupid question, all the literature seems to be focused on JavaBeans
    Any advice on this would be great!

    Beans are used as putting Java code into a JSP is generally considered bad practice. The advantage of the bean pattern is that you use things like:
    <jsp:setProperty name="laBean" property="someSetter" value="someValue" />so that you aren't embedding Java directly into the JSP. I'm not very religious about this particular topic personally and will throw a line or two in here and there.
    Having said that though, you can easily use any Java class in a JSP. You'll have to import it first:
    <%@ page import="java.util.*" %>And then you can easily use it like in a real Java program.

  • How to make a Abap Unit Test Suit with many test classes

    Hi,
    Problem space
    we have different packages(embedded) in our project and each package corresponds to a differnt functional layer in the design.
    We want to create abab unit test classes for these different layers.
    say embedded package 1 has 10 unit test classses
          embedded package 1 has 20 unit test classses
    How to grup these classes together so that we can start them frm a test suite.
    Code examples and blogs links will be appreciated.
    regards
    anubhav

    This sounds a bit like Project Administration 101 to me.
    I'm not exactly sure what you are actually trying to do here --but generally if you want to functionally test something you need to start with a business process -
    You need to create scripts which tell the user the data to be entered, the transaction to be used and the outcome.
    With SAP you might need to show screen shots of each stage as well.
    You follow this for each complete business process until you've covered the whole business cycle.
    You complete this say individually for Logistics, Purchasing and Finance and then compare what SAP gives you with what you expected to get.
    For some type of testing CATTS can help but without the business processes any testing is essentially meaningless.
    It is totally pointless trying to design a "generic" test plan until you've got the functional consultants to describe the business processes involved.
    Cheers
    jimbo

  • Unit Testing, Null, and Warnings

    I have a Unit Test that includes the following lines:
    Dim nullarray As Integer()()
    Assert.AreEqual(nullarray.ToString(False), "Nothing")
    The variable "nullarray" will obviously be null when ToString is called (ToString is an extension method, which is the one I am testing). This is by design, because the purpose of this specific unit test is to make sure that my ToString extension
    method handles null values the way I expect. The test runs fine, but Visual Studio 2013 gives includes the following warning:
    Variable 'nullarray' is used before it has been assigned a value. A null reference exception could result at runtime.
    This warning is to be expected, and I don't want to stop Visual Studio 2013 from showing this warning or any other warnings, just this specific case (and several others that involve similar scenarios). Is there any way to mark a line or segment
    of code so that it is not checked for warnings? Otherwise, I will end up with lots of warnings for things that I am perfectly aware of and don't plan on changing.
    Nathan Sokalski [email protected] http://www.nathansokalski.com/

    Hi Nathan Sokalski,
    Variable 'nullarray' is used before it has been assigned a value. A null reference exception could result at runtime.
    Whether the warning above was thrown when you built the test project but the test run successfully? I assume Yes.
    Is there any way to mark a line or segment of code so that it is not checked for warnings?
    There is no built-in way to make some code snippet or a code line not be checked during compiling, but we can configure some specific warnings not to be warned during compiling in Visual Basic through project Properties->Compile
    tab->warning configurations box.
    For detailed information, please see: Configuring Warnings in Visual Basic
    Another way is to correct your code logic and make sure the code will not generate warning at runtime.
    If I misunderstood you, please tell us what code you want it not to be checked for warnings with a sample so that we can further look at your issue.
    Thanks,
    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.

  • Flash Builder 4.6 - How can I keep unit test classes out of the finished swc?

         I have a library of code I'm building and I'm working on unit testing but I have a major issue. When my finished swc compiles no matter what I do it includes the unit test classes as part of the intellisense if you load the swc via flash. The classes aren't really in the swc since if you just try and import them they'll come up undefined. They only appear to go into the intellisense for the swc. Does anyone know how can I keep this from happening in the finished source? Currently my folder setup is like this in flash builder.
    src\main - source documents for the library to get compiled
    src\mock - mock class area for unit testing
    src\test - unit test classes
         In the project Properties panel > the first tab of my Flex Library Build path I have selected only the src\main folder for the classes to inlude in the library. No other folder paths are selected.
    The "Flex Library Build Path" doesn't change my results with any setting.
    Thanks,

    Mel Riffe,
    Here's a Help topic about compiler options in Flash Builder: http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb524b8220812e5611f28f-7fe7. html
    For information on using mxmlc, the application compiler, to compile SWF files from your ActionScript and MXML source files, you can see: http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7fcc.html
    Hope this helps,
    Mallika Yelandur
    Flash Builder Community Help & Learning
    Adobe Systems Incorporated

  • [svn:osmf:] 12422: Adding null param to URL constructor in unit test.

    Revision: 12422
    Revision: 12422
    Author:   [email protected]
    Date:     2009-12-03 01:43:59 -0800 (Thu, 03 Dec 2009)
    Log Message:
    Adding null param to URL constructor in unit test.
    Modified Paths:
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/metadata/TestCompositeMetadata.as

    To Neoreborn:
    If I understand right, Shale only provides some mock core JSF objects and extends JUnit so that you can do junit test to your java classes.
    What I concern is to test Pages(JSP) rather than java classes. I want to assert component attribute values within all lifecycle including rendered HTML script. Currently, there isn't any good tools to do this kind of JSP Unit test, am I right?

Maybe you are looking for