April 2010


1. Create a unit test with EasyMock:

Class UserManagerTest {
    UserDao mockUserDao;
    Authentication mockAuthentication;
    @BeforeClass
    void init() {
        mockUserDao = EasyMock.createMock(UserDao.class);
        mockAuthentication = EasyMock.createMock(Authentication.class);
   }
   @test
   public void testUpdateUser() {
       //init User
       User user = new user;
       user.setName("test");
       user.setPassword("pass");
       //init isAccess
       boolean isHaveAccess = true;
       //expect
       EasyMock.expect(mockAuthentication.isHaveAccess()).andReturn(isHaveAccess);
       EasyMock.expect(mockUserDao.findUser(1)).andReturn(user);
       EasyMock.expect(mockUserDao.saveUser());
       //replay
       EasyMock.replay(mockUserDao);
       EasyMock.replay(mockAuthentication);
       //call test method
       //if method have return .you should use Assert
       userManager.updateUser(1);
       //call verify
       EasyMock.verify(mockUserDao,mockAuthentication);
   }
}

–> Change to use with

Class UserManagerTest {
    @Mock
    UserDao mockUserDao;
    @Mock
    Authentication mockAuthentication;
    @test
   public void testUpdateUser() {
       //init User
       User user = new user;
       user.setName("test");
       user.setPassword("pass");
       //init isAccess
       boolean isHaveAccess = true;
       //expect
       EasyMock.expect(mockAuthentication.isHaveAccess()).andReturn(isHaveAccess);
       EasyMock.expect(mockUserDao.findUser(1)).andReturn(user);
       EasyMock.expect(mockUserDao.saveUser());
       //replay
       EasyMockUnitils.replay();
       //call test method
       //if method have return .you should use Assert
       userManager.updateUser(1);
   }
}

	
	

I.Enviroment:

Class UserDao {
   User findUser(int id) {...}
   void saveUser(User user) {...}
}
Class Authentication{
    boolean isHaveAccess(){}
}
Class UserManager{
   void updateUser(int id) {
   if(!objectAuthentication.isHaveAccess())
       thow AuthenticationException ;
   validateUserInfo();
   User user = objectUserDao.findUser(id);
   objectUserDao.saveUser(user);
   }
   boolean validateUserInfo() {...}

}

II. Write a unit test to test createUser :

– In createUser method, you see that have two object (objectAuthentication and objectUserDao).But in this unit test, you just focused test behaviour createUser.

Don’t care about test for behaviour authentication and save user.Because you will have another unit test to test these saveUser and check Authentication.So you will create 2 object Authentication and UserDao are a mock object.

1.Create Mock object with EasyMock framework:

– There are 3 type mock Object:

+ Normal – EasyMock.createMock() : All of the expected methods must be called with the specified arguments. However, the order in which these methods are called does not matter. Calls to unexpected methods cause the test to fail.

+ Strick – EasyMock.createStrickMock(): All expected methods must be called with the expected arguments, in a specified order. Calls to unexpected methods cause the test to fail.

+ Nice – EasyMock.createNiceMock(): All expected methods must be called with the specified arguments in any order. Calls to unexpected methods do not cause the test to fail. Nice mocks supply reasonable defaults for methods you don’t explicitly mock. Methods that return numbers return 0. Methods that return booleans return false. Methods that return objects return null.

2. Expecting mock object method calls using EasyMock.expect :

3. Replaying expected method using EasyMock.replay():

If you forget to call EasyMock.replay() before using a mock, you’ll get an IllegalStateException with the not especially helpful error message: missing behavior definition for the preceding method call.

4. Verifying the expected method using EasyMock.verify():

This is the last step create unit test. It will validate all method you expected.

*Finish test:

Class UserManagerTest {
    UserDao mockUserDao;
    Authentication mockAuthentication;
    @BeforeClass
    void init() {
        mockUserDao = EasyMock.createMock(UserDao.class);
        mockAuthentication = EasyMock.createMock(Authentication.class);
   }
   @test
   public void testUpdateUser() {
       //init User
       User user = new user;
       user.setName("test");
       user.setPassword("pass");
       //init isAccess
       boolean isHaveAccess = true;
       //expect
       EasyMock.expect(mockAuthentication.isHaveAccess()).andReturn(isHaveAccess);
       EasyMock.expect(mockUserDao.findUser(1)).andReturn(user);
       EasyMock.expect(mockUserDao.saveUser());
       //replay
       EasyMock.replay(mockUserDao);
       EasyMock.replay(mockAuthentication);
       //call test method
       //if method have return .you should use Assert
       userManager.updateUser(1);
       //call verify
       EasyMock.verify(mockUserDao,mockAuthentication);
   }
}

If anyone read it. Please suggest to me if have anything wrong or need to improve.

From “JUnit in Action”.

1. Logic unit test:

– A test that exercises the code logic by focusing on a single method. You can control the boundaries of given test method using mock objects or stubs.

2. Integration unit test:

– A test that focuses on the integration between components in their real environment ( or part of the real environment ). For example , code that accesses a database has tests that effectively call the database.

3. Functional unit test:

– A test that extend the boundaries of integration unit testing to confirm a stimulus-response. For example, a web application contains a secure web page that only authorized client can access. If the client does not log in, then trying to access the page should result in a redirect to the login page. A functional unit test can examine this case by sending an HTTP request to the page verify the redirect ( HTTP status code 302) response code come back.

Problem:
– when we use datagrid to add new item and edit item directly on grid.
If you don’t sort on datagrid. Everything is ok.
But when you sort on datagrid:
– Adding new Item. The position of new Item will change follow sort.
– And after that. We use another button to Save new Item or item to edit.
The data saved will wrong.Because when save click. the position change again.

Solution:
We create new class extends Sort class of Flex.
Override function findItem() return the position you want.

EX:
public override function findItem(items : Array, values : Object, mode : String, returnInsertionIndex : Boolean =
false, compareFunction : Function = null) : int {
if (_enableSort) {
return super.findItem(items, values, mode, returnInsertionIndex, compareFunction);
} else if (_editedIndex != -1) {
return _editedIndex;
} else
return items.length;
}

From Ben Northrop, Consultant

What could be simpler than property files? In an enterprise application, it turns out, many things! In this post I’ll take a look at a few subtle complexities to managing properties in an enterprise Java Spring application, and hopefully demonstrate how a little fore-thought in design can yield big savings in terms of time, confusion, bugs, and gray hair down the road.

Types of Properties

Before designing an approach to managing property files, it’s critical first to understand the types of properties are to be managed. Here are four characteristics to consider:

  • Are some properties environment specific – in other words, do they have a different value in one environment than another? For example, a database connection string would differ in the TEST environment than it would the PROD environment.
  • Do any properties contain sensitive information, like passwords or credentials, that can’t sit in plain text in the deployment unit (e.g. WAR, EAR)?
  • Do any properties need to be located external from the deployment unit (e.g. on the file system rather than in the WAR, perhaps to be managed by a systems administrator)?
  • Should properties be dynamic, in the sense that they can be updated at runtime (i.e. without requiring a restart of the application)?
  • Each of these special characteristics adds a degree of complexity to applications – necessitating additional infrastructure beyond the simple Java Properties class.

    Spring’s PropertyPlaceholderConfigurer

    Fortunately for us, the Spring framework, with the PropertyPlaceholderConfigurer and PropertyOverrideConfigurer, provides the features and hooks we need to manage these cases (with the exception “dynamic” properties). And true to its philosophy, Spring makes simple things simple, and complicated things possible.

    The PropertyPlaceholderConfigurer allows properties to be pulled in to the application context file. For example, in the simplest case, a property “db.user” defined in database.properties could be pulled into the ${db.user} placeholder:

    <bean id="propertyPlaceholderConfigurer"
    class="edu.cmu.s3.core.service.resource.PropertyPlaceholderConfigurer">
      <property name="locations">
        <list>
          <value>classpath:database.properties</value>
        </list>
      </property>
    </bean>
    
    <bean id="dataSource">
      <property name="user" value="${db.user}"/>
      <property name="password" value="${db.password}"/>
      ...
    </bean>
    

    The PropertyOverrideConfigurer works in the opposite way, pushing properties from property files into properties in the context file (without having to specifically define a place holder – e.g. ${db.user}). These are both well documented in the Spring API and documentation.

    Tips

    Given the different possible types of properties, and Spring’s property framework, here are a few tips for managing them:

    1) Consider using a JVM System property that sets the environment of the machine (e.g. “my.env=TEST”), telling the configurer which property file to use. For example:

      <context:property-placeholder location="classpath:db-${my.env}.properties"/>
    

    If the “my.env” property was set to “TEST”, then obviously the PropertyPlacementConfigurer would look for a file called “db-TEST.properties”. For Tomcat, this property can be set in the admin console or defined in a startup script (e.g. “-Dmy.env=TEST”) – neither of which is very elegant. Alternatively, it is possible to use JNDI with Tomcat, defining “my.env” in the server.xml and the context.xml of the web app. (Note, there are of course many other ways to solve this environment-specific problem, but this is an easy and relatively straight-forward one.)

    2) It may be necessary to set the ignoreUnresolvablePlaceholders to true for any PropertyPlaceholderConfigurer, which will ensure that a configurer won’t fail if it can’t find a property. Why would this be a good thing? Oftentimes, one context file will import other context files, and each may have their own configurer. If ignoreUnresolvablePlaceholders is set to false (the default), then one configure would fail if it couldn’t find the property, even if another configurer down-stream could find it (see good explanation here). Beware, however, since this will suppress warnings for legitimate missing properties, making for some tough-to-debug configuration problems.

    3) To encrypt properties, subclass the PropertyPlacementConfigurer and override the convertPropertyValue() method. For example:

    protected String convertPropertyValue(String strVal) {
      //if strVal starts with “!!” then return EncryptUtil.decrypt(strVal)
      // else return strVal
    }
    

    4) Consider using the systemPropertiesMode property of the configurer to override properties defined in property files with System properties. For one-off environment specific properties this can be a helpful solution, however, for defining many properties, this configuration can be cumbersone.

    5) For properties that need to be managed outside of the WAR, consider using a System property to define where the file is located. For example, the property ${ext.prop.dir} could define some default directory on the file system where external property files are kept:

    <context:property-placeholder location="file:///${ext.prop.dir}db.properties"/>
    

    This entails, however, that this property is set for any process that leverages the Spring container (e.g. add the param to the Run Configuration for integration/unit tests, etc.), otherwise the file would not be found. This can be a pain. To circumvent, the configurer can be overridden – changing the behavior such that it looks to the external directory only if the System property is set, otherwise it pulls from the classpath.

    6) Beware of redundancy of environment-specific properties. For example, if the solution is to have one property file for each environment (e.g. “db-test.properties”, “db-dev.properties”, etc.), then maintaining these properties can be a bit of a nightmare – if a property “foo” is added, then it would have to be added to the property file for each environment (e.g. DEV, TEST, PROD, etc.). The PropertyOverrideConfigurer is appropriate to eliminate this redundancy, setting the default value in the application context itself, but then the overriding value in a separate file. It’s important, however, to document this well, since it can look a bit “magical” to an unsuspecting maintenance developer who sees one value specified in the context file, but another used at runtime.

    Conclusion

    Managing properties for an enterprise application is a little trickier than one might expect. With Spring’s property configurers, however, the toughest part is just knowing what you need – the rest comes out of the box, or with some minor extensions.

Have some option configure to get Data sources.

1. Data sources are defined by JDBC driver:

<bean id=”dataSource” class=”DriverManagerDataSource”>
<property name=”driverClassName” value=”jdbcDriver” />
<property name=”url” value=”url” />
<property name=”username” value=”user” />
<property name=”password” value=”pass” />
</bean>

Use DriverManagerDataSource class.

Returns a new connection every time that a connection is requested.

2. Data sources are gotten from pool connections:

– Data sources are looked up by JDNI.

There are many coverage code tool such as Emma, Cobertura, Clover.

So I choose EMMA because :

– It is open source

– Have plugin for Eclipse IDE and Maven.

Next Page »