Reading JUnit Source Code

@xiaojun-zhang

Preparation and JUnit Basic Usage

First step is to download the JUnit source code, create a new project in Eclipse, and then import the downloaded JUnit code.

Second step is to define the code to be tested. Below is the code, it’s very simple, just calculates the sum of two integers.

public class SimpleClass {
    public static int add(int a, int b) {
        return a + b;
    }
}

Third step is to write the test case. JUnit test cases can be implemented by inheriting the junit.framework.TestCase class. Methods, whose name begins with ‘test’, defined in subclasses of ‘TestCase’ will be treated as test cases. Multiple test cases can form a TestSuite. JUnit4 can also define test cases with @Test annotation.

public class TestSimpleClass extends TestCase {
    public void testAdd() {
        int result = SimpleClass.add(1, 1);
        Assert.assertEquals(2, result);
    }
}

In the above code, the testAdd() method is parsed as a test case. You can also define a test case by defining the suite() method, which isn’t too much difference.

Now we are ready to run and test the code.

JUnit Source Code Structure

Below is JUnit’s package structure:

Package Stucture

The core code is in junit.framework package. Package junit.runner is for running the test cases, in which BaseTestRunner is an abstract class. Package Junit.awtui, junit.swingui, junit.textui are three different graphical interfaces to run test cases, each package has a TestRunner inherited from junit.runner.BaseTestRunner.

The code I red is mainly in junit.framework package, junit.textui package, and the abstract class BaseTestRunner.

Below is the class diagram:

Class Diagram

Running Process of JUnit

JUnit’s running process can be divided into three steps, preparaing test cases, running test cases and collecting test results. In following code, getTest(testcase) is to prepare test cases, doRun(suite, wait) is to run the test cases:

try {
    if (!method.equlas(""))
        return runSingleMethod(testCase, method, wait);
        
    Test suite = getTest(testCase);
    return doRun(suite, wait);
} catch (Exception e) {
    throw new Exception("Could not create and run test suite: " + e);
}

Below is the sequence diagram:

Sequence Diagram

Design Pattern in JUnit

Composite

JUnit uses composite pattern when creating test cases. Junit.framework.Test is the interface that defines the test case, which includes both run() and countTestCases () methods. TestCase and TestSuite are two classes that implement the interface, TestCase is for single test case, and TestSuite is for a collection of test cases.

Observer

Observer pattern is used when collecting test results. junit.framework.TestResult manges a collection of TestListeners, these TestLiteners will be notified when execution of test case is failed.

Manage a collection of TestListener:

/**
* Registers a TestListener
*/
public synchronized void addListener(TestListenser listener) {
    fListeners.addElement(listener);
}

/**
*  unregisters a TestListener
*/
public synchronized void removeListener(TestListenser listener) {
    fListeners.removeElement(listener);
}

When the test case fails to execute, notify TestListenner to handle the errors:

public synchronized void addError(Test test, Throwable t) {
    fErrors.addElement(new TestFailure(test, t));
    for (Enumeration e = cloneListeners().elements; e.hasMoreElements; ) {
        ((TestListener)e.nextElement()).addError(test, t);
    }
}

Template Method

Template mode is relatively simple, it’s used in BaseTestRunner.getTest(), TestCase.runBare().

Link to article on GitHub

Implementing FAQ Bots using Microsoft Bot Framework

 Subitha Sudhakaran

When we build complex apps, the customers or users will have several queries regarding the working of this App. In normal case, we will provide help documents, FAQ or a forum to submit their queries etc. But now the trend is to move to conversational computing. Bots are the emerging mode for conversational computing. We can use Bots to simplify the customer interactions using the services like Skype, mail, Facebook messenger etc. We can consider it as an artificial user. Even if it is an artificial user, it should be smart enough to do the things which replace human activities. But Bots can be smart, semi- smart or dummy based on how we implement it. Artificial intelligence is the key for Smart BOTs.

I have been exploring and working on using Microsoft Bot framework at SequoiaAT, we can build and deploy chat bot’s across different services. It is intended to be cross- platform and cloud-based. Each Bot application is available to the users through a set of channels such as Skype, mail, text etc. Bot connector is the central component that connected our Bot with these channels. You can configure in which all channels your bot should be available. The architecture of a Bot connector is REST based i.e. there is no constraint on framework or the language. The only constraints are given by the endpoint names and exposed behaviour. Bot builder SDK s an open source SDK hosted on Github. There are two SDKs, one for to use with .Net and one for Node.js.

FAQ BOTS – Microsoft is continuing to update their services, adding new features and functions. Now it includes support for Azure Bot services, a cloud based development platform. Microsoft has implemented different templates to make it easier to use. One of the useful templates is “Question and Answer”. This is an ideal template for anyone building a customer service bot because it can work with your FAQs. In many cases, question and answer already exists in contents like FAQ in some documents. QnAMaker tool will allows us to consume the existing FAQ content and expose it as an HTTP endpoint. QnAMaker is a free web based service to respond to the users’ queries in a conversational way. So there is no coding required developing, training and managing the Bot service using QnA Maker.  As an end user you are only required to provide the predefined question and answer to the QnA  and It takes care of the rest. The result will be an endpoint which accepts the questions and returns a json response containing the matching response.

Bot framework is implemented by wiring up with LUIS (Language Understanding Intelligent Serivce). We don’t need to ask the exact question we stored in knowledgebase to get the relevant answer. It will look for keywords and based on the keywords, it provide appropriate responses. Sometimes it may match more than one possible responses. In that case, it will return the answer with high score. QnA Maker will help us to take our existing knowledge base and help us to turn into conversational services.

Pre-requisite for creating a FAQ BOT using the QnA Maker is a Microsoft id to create a QnA Bot service. We can login to the site https://qnamaker.ai/ for creating the QnA Service. Creating the QnA service is a pretty straight forward with minimum steps. One of the advantages I see here is, it is easy to create a FAQ bot for existing applications if we already have FAQ documents in some document format or in deployed in any page. Supported FAQ documents are .tsv, .pdf, .doc, .docx. So basically we can provide this document or page URL as an input while creating the QnA service. We are permitted to provide multiple input files and it will add the question and answer as a key value pair in its knowledge base. For new applications, if we don’t have any FAQ documents already, we create Question answer pair while creating the service itself. It supports testing our service in a conversational way before publishing the service. Once we published the service, we can make simple HTTP calls to call the QnA Maker service from our BOT applications. Basically when a user ask a question, the BOT application will internally pass the user keyword to the QnA service and will check the knowledge base for approximate matching record.

Once you are done creating the Bot application and integrating it with the QnA service, we need to publish that on the Microsoft Azure. For that you need Microsoft Azure subscription. You can get a free trial for limited period. It is possible to publish our Bot application directly from the Visual studio using the Publish option available. We just only need to follow the Publish wizard steps to complete the process. Finally we can see our published application on Microsoft Azure. After publishing, we need to register your Bot with Microsoft Bot framework.

For registering your Bot, you need to sign in https://dev.botframework.com/ using your Microsoft id and click on the register bot option. We need to fill in the details it needs. There we can see a BOT ID and an App Secret .These are used for authenticating our Bot application with the Microsoft Bot framework. Bot interacts with users naturally from your website or from different other channels. Current supported channels are Skype, Slack, Facebook Messenger, Office 365 mail, teams etc. We can decide in which on channel we would like to add our Bot application while registering the BOT. We can select the channels from the list of supported channels. Once you have added your bot to any of these services, it is always online and you can send message anytime and get an instant response.