Archive for August, 2008

Multithreading in C# Windows Form

What I write here was part of the application that we illustrated in this blog during our User Oriented Design lab course in summer semester 07.

 

Having only one thread doing both UI and processing would make the UI becoming unresponsiveness when there is a lot to process. We implemented a C# Windows Form application. There are 2 threads: UI thread and processing thread. 

In the beginning of the development, we did not expect the complexity of writing a multithread application would be very high.

 

1. Starting a thread

Following is an example of the function for a new thread to start.

public static void startClusterImages(object o)

{  mainForm = (MainForm) o;

….

Before I am going to start a thread, I check whether the processing thread has started or not. 

if (!clusterThread.IsAlive)
{

clusterThread = new Thread(threadFunction);
clusterThread.Start(this);

}

 The parameter for the ParameterizedThreadStart is the function that we want the processing thread to start.  I think that you can only pass one parameter. If there are multiple parameters, I suggest that you group all of paramaters into a single object. 

static ParameterizedThreadStart threadFunction = new ParameterizedThreadStart(ImageProcessingControl.startClusterImages);

static Thread clusterThread   = new Thread(threadFunction);

2. Control accessing shared variables

When accessing a shared variable, the lock mechanism is needed. However, I am not quite trusting the lock mechanism. It is better to design in a way which avoids using a shared variable.

Anyway, the “lock” keyword can be used to lock an object. The SyncRoot property of the object is used for locking.

lock (uodImageArrayList.SyncRoot)
{

}

3. Invoke a function in UI thread from another thread.

The processing thread can not directly invoke a function in a MainForm class which is in the UI thread. Following code is the way to access a function in the UI thread from the processing thread.

First, Check whether the call is from the UI thread or not. If this.InvokeRequired returns false, that means the call is from the UI thread. In this case, there is no problem.

However, if the call is not from the UI thread,  this.InvokeRequired  returns true. It will go to “else” statement and call BeginInvoke which it will call this setSelected_UODImageGroupUserControl  function again eventually. Somehow, the call thread will be switched to the UI thread, so when this setSelected_UODImageGroupUserControl   function is called again from beginInvoke, it is called from the UI thread.  

public delegate void setSelected_UODImageGroupUserControl_delegate(UserControl userControl);

public void setSelected_UODImageGroupUserControl(UserControl userControl)
{

if (this.InvokeRequired == false)
{

//If this function is called from the same thread (UI Thread).
//then proceed

this.currentlySelectedUserControl = userControl;
this.copyToolStripMenuItem.Enabled = true;
this.cutToolStripMenuItem.Enabled = true;
this.deleteToolStripMenuItem.Enabled = true;
this.toolStripStatusLabel1.Text = ” “;

 

}
else
{

//If this function is called from different thread
//Then call the delegate first
//The delegate will somehow route this request to be in the UI thread
this.BeginInvoke(new setSelected_UODImageGroupUserControl_delegate(

setSelected_UODImageGroupUserControl), new object[] { userControl });

 

}

}

Add comment August 23, 2008

Usability Design Lab

I took a User Oriented Design lab course in summer semester 07. Students were seperated into groups. There are three students including me in our group. I and two friends decided to do an image groupping application. Basically, students develop a usability product. I would like to summarize our result here, so I won’t forget what we did and how much usability which we have approved on our image groupping application.

Basically, the application would group similar images into a group. The groupping algorithm is based on time and visual similarity. We are not really good at groupping algorithm, so I won’t talk much on this aspect. On the usability aspect, we have made two prototypes. The first prototype is shown below.

Our first prototype

Our first prototype

At first, we just think that there should be a panel that we put images in. Then, there is a button which starts groupping images into groups and displaying groupping images on the new panel. The first prototype also has the problem of unresponsiveness, because there is one thread for both UI and images groupping processing.  The figure below shows when we loaded a lot of images which took some processing time, and the interface is kind of not responding. When groupping images, if there are a lot of images, the user interface is kind of not responsive. One way that we can improve usability is to seperate another thread for processing images such as loading or groupping. That’s all we can think.

We discussed the first prototype with the lab assistant. She made a good suggestion on which other way we can improve usability. She suggested that there is two steps when using the first prototype which were loading and groupping. There is no need to display images on the right panel. The ultimate goal of user is to group images. It is better that when images are load, the application automatically groups them instead of waiting for a user to click on the “classify” (groupping images) button.

Second of all, it should display the result immediately without waiting for the groupping of all images. The images which have been grouped should be displayed immediately on the application. Therefore, a user does not have to wait until all images groupping is finished which could take quite a great deal of time if there is a lot of images.

The first prototype displays in a group on a same row. Vertical scrollbar is often required to see other image groups. Horizon scrollbar is required to see other images in a group. The third suggestion was to display only thumbnails of images. The first picture on the thumbnail represents its image group. Perhaps, there is a stack of images displaying behind the thumbnail, so a user can have a sense of how many images in that group. The figure belown shows the second prototype. Thumbnails of group of images are displayed. When a user clicks on a thumbnail, images in that group are displayed in the second panel.

Our second prototype

Our second prototype

It is really interesting that usability can be significantly improved.

Note: the application was implemented with C#.

1 comment August 23, 2008

Some Error messages when trying out WCF

Some error messages (e.g. InvalidOperationException, configuration binding extension not found, etc.) that I found when I was trying WCF. I listed in here in hope that it would be useful later if entercountered.

Continue Reading 3 comments August 19, 2008

WCF And MSMQ Part 1

Messaging technology allows a client and a server to send a message to each other, and they do not have to run at the same time. One party can send a message to another party at anytime. A crash on one side does not effect the another side.

In this tutorial, I am going to implement a simple WCF client-server application without any consideration on security. We are going to use MSMQ as a transport mechanism. I use Microsoft Visual Studio 2008. Please read Queuing in WCF msdn page for further information. Note: you have to install MSMQ on your computer.

Please refer to this msn page for what is WCF (Windows Communication Foundation) and what does it solves.

Please refer to this msdn page for various WCF technical term.

Each WCF service has an endpoint. An endpoint consists fo address, binding and contract.

- An address is usually a URI which specifies where the endpoint of the service is. 

- A binding defines the transport mechanism between a client and a server. There are some predefined bindings avaiable. In this tutorial, we are going to use MSMQ as a transport mechanism, so we are interested in NetMSMQBinding.

- A contract is your service, and it is implemented in C# in this tutorial.

Steps:

1. Create a server project

Create a server project by simply select a C# console application from “New Project” dialog.  Let’s name the solution name as wcf_tutorial” and the server project name as WCFServer1.”

New project and new solution dialog in Visual Studio 2008

New project and new solution dialog in Visual Studio 2008

Please refer to “How to Add or Remove References in Visual Studio” msdn page for how to add a reference.

You need to add two references which are System.messaging (found in .NET tab when opening up the “Add Reference” dialog) and System.ServiceModel.dll (found in “C:\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation” in Windows folder, click on “Browse” tab in the “Add Reference” dialog).

2. Create server source files

 

IWork is an interface which will be configure as a contract in a binding configuration. WorkService is the implementation of this contract. The server does nothing. It just receives a string from a client.

Please refer to How to: Define a Windows Communication Foundation Service Contract msdn page for how define a contract. Please remember than a MSMQ is a messaging technology which is anynchronous communication. There is no respond back from a server like web service. Thus, the function has no return type which is “void.”

- Please refer to Build a Queued WCF Response Service for more information on WCF and MSMQ. 

- Please refer to How to: Implement a Windows Communication Foundation Service Contract msdn page for how to implement a contract.

//////Program.cs//////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Messaging;
using System.Configuration;

namespace WCFServer1
{

[ServiceContract(Namespace = "http://sukasom.wordpress.com")]
interface IWork
{

[OperationContract(IsOneWay = true)]
void submitWork(String str1);

}

public class WorkService : IWork
{

public void submitWork(String str1)
{

Console.WriteLine(“Server has received a work : “ + str1);

}

}

class Program
{

static void Main(string[] args)
{

 

string queueName = ConfigurationSettings.AppSettings["queueName"];

if (!MessageQueue.Exists(queueName))
MessageQueue.Create(queueName, true);

using (ServiceHost serviceHost = new ServiceHost(typeof(WorkService)))
{

serviceHost.Open();

Console.WriteLine(“The service is ready.”);
Console.WriteLine(“Press <ENTER> to terminate service.”);
Console.ReadLine();

}

 

}

}

}

Put the above code in the Program.cs.  The server part is modified from How to: Host a WCF Service in a Managed Application msdn page.

3. Configure server configuration file

You need to configure the configuration file. Add an App.config file into your project. Please refer to Specifying an Endpoint Address msdn page for more information on address configuration. My configuration file is modified from NetMSMQBinding msdn page.

Configuration of WCF service using MSMQ as a transport mechanism

Configuration of WCF service using MSMQ as a transport mechanism

///////////////App.config /////////////////////////

<?xml version=”1.0” encoding=”utf-8?>
<configuration>

<appSettings>
<add key=”queueName” value=”.\private$\ServiceModelSamples/>
</appSettings>

<system.serviceModel>
<services>

<service name=”WCFServer1.WorkService” behaviorConfiguration=”Behavior1>

<endpoint address=”net.msmq://localhost/private/ServiceModelSamples
binding=”netMsmqBinding” bindingConfiguration=”test
contract=”WCFServer1.IWork/>

</service>

</services>

<!– Following is necessary for getting information about the service through http with the svcutil.exe tool. –>
<behaviors>
<serviceBehaviors>

<behavior name=”Behavior1>

<serviceMetadata httpGetEnabled=”true” httpGetUrl=”http://localhost:8000/Hello//>

</behavior>

</serviceBehaviors>
</behaviors>

<!– For first example, the security is just disabled. –>
<bindings>

<netMsmqBinding>

<binding name=”test>

<security mode=”None>
</security>

</binding>

</netMsmqBinding>

</bindings>

</system.serviceModel>

</configuration>

In the “service” element, an endpoint is defined with an address, a binding and a contract. This WCF sample application uses MSMQ as a transport mechanism, so the binding is the NetMsmqBinding. 

The contract specifies the interface which is WCFServer1.IWork. The security is turned off in this tutorial through the bindingConfiguration named “test.”

A client needs to be able to access the metadata of the service, so  it is defined through the behaviorConfiguration  named “Behavior1″ where the httpGetEnabled attribute is set to true. It means that  the metadata can be retrieved through the http through the URL set in the httpGetUrl attribute which is “http://localhost:8000/Hello/” in this tutorial. This URL allows the client to get a metadata about the service from the correct location. You can open up the http://localhost:8000/Hello/ on the browser as shown below.

Metadata on the service

Metadata on the service

More info on address and httpGetEnabled can be found in WCF Part 6 : Address blog.

4. Implement the client project.

Start a visual studio 2008 and add a new C# console project as shown in the figure below. The name of the project is “WCFClient1.” Just like the server part, add the reference to System.ServiceModel.dll. More info on accessing service through a client at Accessing Services Using a WCF Client msdn page.

Add new project into an existing solution in microsoft visual studio 2008

Add new project into an existing solution in microsoft visual studio 2008

5. Generate a client proxy.

The ServiceModel Metadata Utility Tool (Svcutil.exe) is needed to generate the proxy file for a client. The proxy file allows you to treat a remote service as a local service. You simply instantiate a remote object and call a function on it. This is much simple compared with some old distributed technologies.

Please refer to ServiceModel Metadata Utility Tool (Svcutil.exe) msdn page for the manaul of Svcutil.exe.

Please start the server first then type the following command in the command prompt.

“C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcUtil.exe”  http://localhost:8000/Hello/

The URI is the URI that is defined in the App.config in the server part. After running the above command, you will get two files which are WorkService.cs and output.config.

Generating a proxy file for a WCF client project using SvcUtil.exe

Generating a proxy file for a WCF client project using SvcUtil.exe

Please rename the output.config to App.config. Copy those two files into your project directory, and add those files into your project.

Following is the code for the client:

////////////Program.cs in the client part/////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WCFClient1
{

class Program
{

static void Main(string[] args)
{

WorkClient wc = new WorkClient();
wc.submitWork(“hello work 1″);

}

}

}

Calling a server is very simple, instantiating the proxy object and calling a function on it. You can see that there is a class called WorkClient defined in the WorkService.cs. Please run the server first. If the queue has not been created, it will be created. When the queue is created, you don’t have to run the server before running the client. You can run the client first, and the message from the client will be stored in the queue. The message will be sent to the server when the server is started again.

 

Server part

Server part

You can take a look Tom Hollander’s blog for another good tutorial on this topic.

Here is the complete source code.

The book from [Lowy] is also good.

1 comment August 18, 2008

JMS Topic

I had taken a lab course with this department. Without the lab assistant, I would not make it through. I would like to summarize a part of my lab work here related with JMS, so I will not forget. Full lab report here.

Following is the general architecture of  the system. JMS is used for communication between the NodeController and a Node Client.

 

The Overview Architecture of the Job Spooling System

The Overview Architecture of the Job Spooling System

 

 

I was doing a distributed application in Java. Part of the lab is sending a message from an EJB (version 3) to a client application on a different machine using JMS (Java Message Service).  First, we have to create a JMS Topic which is kind of a channel that we send can send a message too. Naming this technology with the word “Topic” is not a good idea, because this word is a common name. Thus, it is difficult to search for examples in Google.

 

I was using JBoss 4. I had to create a JMS Topic in the JBoss first by going to the JMX console of JBoss. I assume that you know how to install JBoss, and develop  EJB 3.0 applications.

1. Go to JBoss homepage at http://localhost:8080. The URL could be something else that you have set.

2. Go to JMX console by clicking at JMX Console under JBoss management.

3. Go to DestinationManager under jboss.mq.

4. Create a JMS topic named “pomtopic” by invoking the createTopic function. Supply param p1 and p2 with the value “pomtopic,” and then click “Invoke” as shown in the figure below. The “pomtopic” topic will be
created. Java application can send message to and receive message from this JMS topic.

I am not sure why there are two paramters (p1 and p2). Just try to use the same name. The name could be something else. The name will be referenced from the codes.

Creating a JMS Topic within a JMX Console of JBoss 4. Clicking invoke will create a JMS Topic.

Creating a JMS Topic within a JMX Console of JBoss 4. Clicking invoke will create a JMS Topic.

Following is the sender code of the JMS Topic. The sender code is in the EJB 3.0. Some variables are declared and instantiated automatically though dependency injection technique.

==========sender=============================

……

// Connection factory for JMS Topic communication
@Resource(mappedName=”TopicConnectionFactory”)
private ConnectionFactory connectionFactory;
//For JMS Topic communication, the name of JMS Topic is fixed to “pomtopic”.
//This topic must be created in JBoss JMX console before using, otherwise, it will throw an exception.

@Resource(mappedName=”pomtopic”)
private Topic topic;

// This function will send the message to the JMS topic.
//Derived from the JMS tutorial from Sun website
// @param msg represents the message that this function will send to the JMS topic which node client is //listening to.
//@return result of sending, True for successfully. False for when there is an exception occurred.

public boolean sendMessageToTopic(String msg)
{

try {

Connection connect = connectionFactory.createConnection( );
Session session = connect.createSession(true,0);
MessageProducer producer = session.createProducer(topic);
TextMessage textMsg = session.createTextMessage( );
textMsg.setText(msg);
producer.send(textMsg);
connect.close( );

 

} catch (JMSException ex) {

logger.debug(ex.getMessage());
return false;

 

}
return true;

 

}

….

==================================================

 

Next is the client code who is waiting for message. First, you need to create a connection to the JMS Topic first. The Java function below demonstrates the connection.

=====client : function for creating a JMS Topic connection=============

public  void connectByTopic() {

String                  topicName = null;
Context                 jndiContext = null;
TopicConnectionFactory  topicConnectionFactory = null;
TopicConnection         topicConnection = null;
TopicSession            topicSession = null;
Topic                   topic = null;
TopicSubscriber         topicSubscriber = null;

/*  Part of Code from Sun
* Create a JNDI API InitialContext object if none exists
* yet.
*/

try {

jndiContext =getInitialContext();// new InitialContext();

} catch (NamingException e) {

System.out.println(“Could not create JNDI API ” +
“context: ” + e.toString());
e.printStackTrace();
System.exit(1);

}

/*
* Look up connection factory and topic.  If either does
* not exist, exit.
*/

try {

topicConnectionFactory = (TopicConnectionFactory)
jndiContext.lookup(“TopicConnectionFactory”);
topic = (Topic) jndiContext.lookup(“pomtopic”);

} catch (NamingException e) {

System.out.println(“JNDI API lookup failed: ” +
e.toString());
e.printStackTrace();
System.exit(1);

}

/*
* Create connection.
* Create session from connection; false means session is
* not transacted.
* Create subscriber.
* Register message listener (TextListener).
* Receive text messages from topic.
* When all messages have been received, enter Q to quit.
* Close connection.
*/

try {

topicConnection = topicConnectionFactory.createTopicConnection();
topicSession =  topicConnection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
topicSubscriber = topicSession.createSubscriber(topic);
topicSubscriber.setMessageListener(this);
topicConnection.start();

 

} catch (JMSException e) {

System.out.println(“Exception occurred: ” +
e.toString());

} finally {

if (topicConnection != null) {
try {
topicConnection.close();
} catch (JMSException e) {}
}

}

}
==================================================

After creating a JMS Topic connection, then the Java client application needs to listen for a message.

=========Client : function for listening a JMS Topic message==========

public void onMessage(Message message) {

TextMessage msg = null;
try {

if (message instanceof TextMessage) {

msg = (TextMessage) message;
System.out.println(“Reading message: ” +
msg.getText());

//the following function will process the message sent from the server
processMessageAndExecute(msg.getText());

 

} else {

System.out.println(“Message of wrong type: ” +

message.getClass().getName());

}

} catch (JMSException e) {

System.out.println(“JMSException in onMessage(): ” +
e.toString());

} catch (Throwable t) {

System.out.println(“Exception in onMessage():” +
t.getMessage());

}

}

=================================================

Add comment August 18, 2008

Quick overview on Cobertura (Testing Coverage Tool)

I have mentioned Cobertura in this blog.

Cobertura is a tool similar to Coverlipse mentioned in this blog. Cobertura is a measurement tool to measure your unit tests’ coverage on your tested codes. I think that it is really a good tool. It is a bit difficult for a beginner, because it requires some configuration. You have to know how to use Ant (a build tool).  Here, I just provide a tutorial to get a quick overview of the Cobertura on Windows.

1. You need to have Ant installed on your computer. You can download from this page. Select apache-ant-1.7.1-bin.zip.  See this page for installing instruction. Be sure to add Ant to your environmental variable called PATH as illustrated in “Windows / OS 2″ section in the installing instruction page, so you can call Ant from any folders. After you install ant, try running just command “ant” in any folder in your command promt. If it displays something like Ant is not recognized as a command, it means that you have not set up the environment variable PATH correctly. See this page for instruction on how to set an envrionmental variable on Windows.

2. download the Cobertura from this page. Select cobertura-1.9-bin.zip.

3. Unzip into your folders. You will get cobertura-1.9 folder

4. Put your Java source files into the example folder. There is an example found in \cobertura-1.9\examples\basic. I put my Java source files which have been used as an example in this blog and this blog. It consists of one Java file, DoSomething.java, and its test case file, TestCountCharacter.java. Basically, put your codes in \cobertura-1.9\examples\basic\src folder.

Put your java files (unit test case and class to be tested) in the cobertura-1.9\examples\basic\src folder

Put your java files (unit test case and class to be tested) in the cobertura-1.9examplesasicsrc folder

5. Put JUnit.jar into \cobertura-1.9\lib.

See this blog for how to get JUnit.jar.

If you do not put this Jar file here, then build will be failed, because it can not compile some classes which use come classes found in JUnit.jar. The error is shown below. If your Java compiler can find JUnit.jar, then you do not need to add JUnit.jar into the lib folder.

Ant build is fail because JUnit has not been added into the lib function.

Ant build is fail because JUnit has not been added into the lib function.

6. Modify the ant build file found in \cobertura-1.9\examples\basic\build.xml.

On the line around 90, add your java test file into it. In my case, I have to add TestCountCharacter.java which contains the JUnit test cases, so I put “<include name=”TestCountCharacter.java” />” as shown below.
<batchtest todir=”${reports.xml.dir}” unless=”testcase”>
<fileset dir=”${src.dir}”>
<include name=”**/*Test.java” />
<include name=”TestCountCharacter.java” />
</fileset>
</batchtest>

7. Run the ant build file simply by typing “ant” in the \cobertura-1.9\examples\basic.

Behind the scene, Cobertura compiles, run test cases and produces the report on your test case coverage. See this page for full instruction.

Ant build success

Ant build success

8. View the report. Reports are automatically generated after the ant build. There are two reports: report on JUnit test case and report on test coverage.

You can view the report of your JUnit test case by opening up the index file in cobertura-1.9\examples\basic\reports\junit-html.

You can view the report of your test coverage by openning up the index file in cobertura-1.9\examples\basic\reports\cobertura-html.

Report on JUnit test cases is automatically generated and can be found in this folder

Report on JUnit test cases is automatically generated and can be found in this folder

Report on your test cases' coverage is automatically generated and can be found in this folder

Report on your test cases

As you see from the figure below, the line coverage is not 100% achieved because there some statements which have not been executed. The branch statement does not achieve 100% coverage, because there is a branch which has not been executed.

Cobertua report displays the test cases' coverage which are line coverage and branch coverage

Cobertua report displays the test cases

If you furhter click into the class DoSomething.java, it shows you which line has not been executed and how many time that line has been executed as shown below.

Cobertura shows test coverage (line (or statement) and branch)

Cobertura shows test coverage (line (or statement) and branch)

2 comments August 16, 2008

How to get JUnit.jar

If you do not have JUnit.jar in your computer, you can download from here. Just download any junit-x.x.jar where x is a version number. The Junit.jar is in the downloaded zip file.

2 comments August 16, 2008

Testing coverage with Cloverlipse in Eclipse 3.2

You want to make sure that your test cases have executed every thing in your function. You can use test coverage criteria (eg. statement, brance, data flow, etc) as a criteria to measure the quality of your test cases.

Or, you can use it to study old codes when you want to see which lines or functions are used without going through a cumbersome debugging process.

This article is continued from the previous tutorial of using JUnit in Eclipse. If you want to see the testing coverage, you can click as shown below.

Run JUni test with Coverclipse

Run JUni test with Coverlipse

I think that Coverlipse is based on statement coverage. There are many test coverage or aquadecy criterion. More info on test coverage can be found in wiki. Basically, you want to test everything in your code. To satisfy statement coverage, you need to execute all statements. To satisfy branch coverage, you need to execute all brances.  Coverclipse shows you which statement is executed by putting a green check on that line as shown below.

After running JUnit with coverclipse, the Coverclipse the line of code which you test case has executed by putting a green check on that line

After running JUnit with coverclipse, the Coverlipse the line of code which you test case has executed by putting a green check on that line

To see a test coverage clearly, I have modified the function that I tested. The function does not mean to do anything make sense. It just serves as an example for code coverage. As you can see below, there are some codes which are not excuted by test cases. It is shown by a red exclamation side on that line.

Coverclipse shows you which lines are not covered by your test cases by putting a red exclamation sign (!) on that line

Coverlipse shows you which lines are not covered by your test cases by putting a red exclamation sign (!) on that line

With Coverlipse, you can use to see which codes are used when you have to study bunch of old codes. It can give you a quick overview than going through a debug processes.

1 comment August 16, 2008

Unit testing with Eclipse and JUnit

Software testing is necessary to ensure the quality of the software. I would like to how can you make  a quick unit test in Eclipse using JUnit.

First of all, there are 2 main kinds of testing : blackbox testing and whitebox testing. Blackbox testing is when you derive a test case for a function without considering codes inside the function. You only care that you provide all possible inputs. There are many blackblox testing techniques. One of them is Category Partition Testing. Bascially, you simply divide all inputs into classes, and then just test one representive input of each class. For example, if a function X has an input of type Integer. You may partition this input into three classes which are negative numbers, zero and postive numbers. This is just an example. Partitioning inputs is depended on your function. Then you derive three unit test cases. One for each partition. If you have 2 inputs. Then you may have 2*3 = 6 combinations of inputs. Sometimes, you may have a lot of combination than you can possibly test. The slides (slides 15) and the paper Category Partition Testing suggest the use of constraint to limit some combinations.  There could be some possbile combination which will not happen for sure, so it can be considered as a constraint and removed out from testing.

Enough with the theory.

I use Eclipse 3.2 and it is already equiped with JUnit. We are going to use some classes from JUnit.jar. You may need to add the JUnit jar file into your Eclipse project if it does not automatically add JUnit into your project build path. (If Eclipse does not add JUnit into your project build path, then your Java class which requires classes found in JUnit.jar can not be compiled.) This  page gives you some idea of how to add JAR file in Eclipse. See this blog for how to get JUnit.jar.

You need to have a Java function that you want to test. A figure below shows an example of Java function.

a simple java function that you want to test

a simple java function that you want to test

Next, you can add a Junit test as shown below.

Adding a new Junit test case

Adding a new Junit test case

Then the “New JUnit Test Case” dialog is shown as illustrated below. You can select a class that you want to test in the textbox “Class under test.”

"New JUnit Test Case" dialog is shown

Next, then you can select a function that you want to test.

Selecting a function that you want to test

Selecting a function that you want to test

You will see a new Java class as shown below. Eclipse  may not be able to recognize some classes as shown below.

Eclipse does not recognize some classes found in JUnit.jar

Eclipse does not recognize some classes found in JUnit.jar

So you need to either add a JUnit jar file into your project. Or, eclipse may ask you whether you want to add Junit.jar into your classpath as shown below.

Eclipse asks whether you want to add JUnit.jar into the build path

Eclipse asks whether you want to add JUnit.jar into the build path

You may add more test cases. In the figure below, I have 4 test cases just for one function. Each test case is represented by one function. A function name needs to be started with the word “test.”  You can simply runs the JUnit as shown below. Normally, you use the assert something function to assure the result from the function. For example, if you expects that a function returns 3 given your inputs, then you assert like following:

assertTrue(returned_value == 3) ;

If the function returns 3, then this test case is passed. Otherwise, it is failed. Deriving test cases and keeping it for further use is a good idea. Developers usually have a version. With JUnit test cases, they can see if a new version of the function still working properly.

The figure below shows when all unit test cases are passed.

result of running JUnit test cases. In this case, all test cases are passed

result of running JUnit test cases. In this case, all test cases are passed

3 comments August 16, 2008

Article on WCF performance

Interesting article from Microsoft about comparing performances between WCF (Windows Communication Foundation) and existing .NET distributed technology.

http://msdn.microsoft.com/en-us/library/bb310550.aspx

Add comment August 15, 2008

Previous Posts


Categories

Top Posts

Recent Posts

Pages

Archives

 

August 2008
M T W T F S S
« Jul   Sep »
 123
45678910
11121314151617
18192021222324
25262728293031

Blogroll

Books

Blog Stats

Top Clicks

Category Cloud

database Distributed application Education emergency response entrepreneurship firefighter (Feuerwehr) Flex/Flash German Language (Deutsch) Java Microsoft and .NET Risk Management (Disaster) Software Testing Uncategorized User Interface Design and Technology wcf Windows Workflow

Spam Blocked