Skip to main content

Mocking .NET WebServices with Mockito

Mocking objects is not a new concept, especially when you want to test classes which refers complex objects you will end up constructing these objects by hard coded values! There are many open source frameworks available for mocking objects in your test classes, but here I am going to explain how we can mock your WebService client.

Before we begin, let me give you an introduction to object mocking.

What is Mocking?

Mocking is nothing but mimicking behaviours of real objects in a controlled way. Normally we mock objects which are complex in nature, to test the behaviour of other objects.

Why mocking objects?

There are many reasons for mocking objects such as
  • constructing an object is too complex, many dependencies
  • takes much time to return the results
  • behaviour is not predictable

What are the popular mocking frameworks in Java?

There are many open source frameworks available in Java such as
  • jMock
  • EasyMock
  • Mockito
  • SevenMock
  • JMockit
  • rMock
  • Unitils
EasyMock and Mockito has simple syntax and easy to read, they are the most feature-rich frameworks currently available.

Mocking a .NET WebService

Let us use the .NET StockQuote WebService available under http://www.webservicex.net/stockquote.asmx

The steps involved are:
  1. generate stubs
  2. write a client for the stock quote WebService
  3. write a jUnit test class
  4. mock the client with Mockito
  5. test the client

Generating JAX-WS Stubs

Let us use wsimport to generate JAX-WS stubs:

wsimport -verbose -p com.techmindviews.webservice.stockquote 
 -Xnocompile -target 2.1 http://www.webservicex.net/stockquote.asmx?wsdl

The following files will be generated:

com\techmindviews\webservice\stockquote\GetQuote.java
com\techmindviews\webservice\stockquote\GetQuoteResponse.java
com\techmindviews\webservice\stockquote\ObjectFactory.java
com\techmindviews\webservice\stockquote\StockQuote.java
com\techmindviews\webservice\stockquote\StockQuoteSoap.java
com\techmindviews\webservice\stockquote\package-info.java

Writing WebService client

Let us write a client for the StockQuote service, let us name it StockQuoteClient.java

public class StockQuoteClient {
 private static StockQuoteClient INSTANCE;
 private static StockQuoteSoap stockQuoteSoap;
  
 public static StockQuoteClient getInstance(String wsdlURL) {
  if(INSTANCE == null)
   INSTANCE = new StockQuoteClient();
  StockQuote stockQuote = new StockQuote(new URL(wsdlURL),
   new QName("http://www.webserviceX.NET/", "StockQuote"));
  this.stockQuoteSoap = stockQuote.getStockQuoteSoap();
  return INSTANCE;
 }

 public String getQuote(String quoteID) {
  return stockQuoteSoap.getQuote(quoteID);
 }
}

So, our WebService client is ready!

Writing test case for the WebService Client

Let us write a test class for the client:

@RunWith(JUnit4.class)
public class StockQuoteClientTest {
 @org.junit.Test
 public void testStockQuote() {
  StockQuoteClient stockQuoteClient = StockQuoteClient.getInstance("http://www.webservicex.net/stockquote.asmx?WSDL");
  String quote = stockQuoteClient.getQuote("GOOG");
  System.out.println("Stock Quote for Google:"+quote);
 }

}

So, you have a WebService client and a test class for the dotNET WebService. Assume the provider charges you each time you invoke the service or the service is available only for a few hours. Your build will fail to test this service and thus you cannot proceed with your development. You have an option to add @Ignore annotation to the test class or method but how to proceed if other test classes are dependent on the result returned by the WebService?

Mocking the client and testing

Mockito is a simpler and better mocking API which is capable of mocking concrete classes as well as interfaces. Just include the maven dependency in your pom.xml file:
<dependency>
  <groupid>org.mockito</groupId>
  <artifactid>mockito-all</artifactId>
  <version>1.9.0</version>
 </dependency>
What to mock?

Here, we are getting an instance of StockQuoteSoap from StockQuote, so let us mock StockQuoteSoap. Don't forget to import Mockito.
import static org.mockito.Mockito.*;

this.stockQuoteSoap = mock(StockQuoteSoap.class);
        when(stockQuoteSoap.getQuote(anyString()))
  .thenReturn("<stockquotes>
   <stock>
    <symbol>GOOG</Symbol>
    <last>629.64</Last>
    <date>1/12/2012</Date>
    <time>4:00pm</Time>
    <change>0.00</Change>
    <open>N/A</Open>
    <high>N/A</High>
    <low>N/A</Low>
    <volume>100</Volume>
    <mktcap>203.9B</MktCap>
    <previousclose>629.64</PreviousClose>
    <percentagechange>0.00%</PercentageChange>
    <annrange>473.02 - 670.25</AnnRange>
    <earns>29.337</Earns>
    <P-E>21.46</P-E><name>Google Inc.</Name>
   </Stock>
  </StockQuotes>");
 
That's it! Whenever you invoke the getQuote() method of StockQuoteClient, the pre-defined XML will be returned! You can customize this code to read the XMLs from file system based on the string passed.

About the Author

Sunil is a technical writer for more than 8 years with good knowledge in enterprise architecture and web technologies. He writes about latest technologies, social media and search engine optimization.

Sunil's Google Profile

Related Articles

Comments

Popular posts from this blog

HDFC Bank introduces Missed Call Service to know Account Balance

Missed call is a powerful business tool in developing countries like India where customers give a miss call to specific phone numbers for getting account details, providing feedback, voting etc. On receiving a missed call from a registered phone number, the underlying app performs a phone number lookup and sends the data to the caller via text message(SMS) or records the call details for future processing.HDFC Bank recently introduced missed call service for its retail customers which allows to retrieve bank account details, mini statement etc. by simply giving a miss call to their toll free numbers.Following services are now available: 1800 270 3333 - Account Balance 1800 270 3355 - Mini Statement 1800 270 3366 - Request for new Cheque Book 1800 270 3377 - Request for Bank account statement Also you can download HDFC Mobile Banking Application by giving a missed call to : 1800 270 3344. Other banks providing missed call serviceAxis bank(known as Axis Dial) - 09225892258Bank of India…

Induction Cooker Showing an Error Code? Induction Cooker Error Codes Explained

Are you searching for Induction Cook-top error codes? Here you can find the error codes of all popular induction cooktops and how to troubleshoot it.

These are for your reference only, do not try to open your cooktop without proper safety measures, we advise you to call the service person if any servicing is needed.

If you want to know how Induction Cook-top works, read our previous article titled What is Induction Cooker? How Induction Cooker Works?.

Whirlpool Induction Cooker Error CodesError CodeErrorSolutionF0An internal error was detected.Disconnect power. Wait 5 seconds before reconnecting power. If the symbol appears again, call for service.F2The surface cooking area is too hot and has turned off.Remove the pans from the surface cooking area. "F2" will disappear when the surface cooking area has cooled. If you turn the surface cooking area back on and "F2" reappears, the cooktop is still too hot. Turn off the surface cooking area and allow it to cool.F4The po…

LICHFL - Generating Home Loan Statements Online

Generating an online statement from LIC Housing Finance Ltd is very easy, simply follow the below steps to create an online account with LICHFL and generate statements online! You may use the online generated statement as a proof for principal paid for a housing loan(under section 80C) and interest paid(under section 24) while filing income tax returns.* Want to know how to save maximum income tax? Read our most read article how to save maximum income tax (opens in new tab).* Paying high interest to LICHFL? Learn how to reduce interest on your existing home loan (opens in new tab).
Before reading further, make sure you have the following information with you: Your Loan Account NumberSanctioned AmountStep 1 - Open LICHFL websiteVisit LICHFL website and click on the 'New Customers? Click Here' link(refer the below screenshot). Step 2 - Enter your loan account detailsFill in the following details: New Loan NumberSanctioned AmountDate of BirthSecurity Codeand click on the Submit b…