Skip to content

hirohitokato/HKLSocketStubServer

Repository files navigation

HKLSocketStubServer License MIT

HKLSocketStubServer is a fake TCP server for iOS testing.

Can register fake response by expect or stub.

// e.g.) Respond a string if incoming data start with the string
[[[server expect] forDataString:@"incoming data(left-hand match)"] respondsString:@"response data"];
// e.g.) Response a data when 3-way handshake is finished
NSData *data = [@"did connect.\0" dataUsingEncoding:NSUTF8StringEncoding];
[[[server expect] respondsWhenAccepted:data];

This is strongly inspired by awesome NLTHTTPStubServer which is written by yaakaito.

Features

  • Fake TCP server runs on iOS device/simulator
  • Responds a specified data for specified incoming data via TCP
  • Uses a prefix search

System requirements

  • iOS 6.0 or higher (older version may be also available, but not tested yet)

Installation

If you install HKLSocketStubServer manually, then just add HKLSocketStubServer subdirectory to your project.

I'm preparing CocoaPods spec now...

Usage

Write the following code at the top of your TestCase.

#import "HKLSocketStubServer.h"

The most simply test example using GCDAsyncSocket is as follows.

  • Get the shared server. the default URL is localhost:54321.
  • register the response data for specified data
  • Send a data to HKLSocketStubServer via TCP. Receive the response.
  • Verify the all expects are invoked

Saying it simply, you change the server URL from real to fake.

static dispatch_semaphore_t _sem_testResponse;
static NSString *_str_response;

- (void)testResponse
{
    HKLSocketStubServer *stubServer = [HKLSocketStubServer sharedServer];

    // Register fake response for incoming "foo" string
    [[[[stubServer expect] forDataString:@"foo"] respondsString:@"bar"];

    // GCDAsyncSocket: Setup async socket.
    GCDAsyncSocket *sock = [[GCDAsyncSocket alloc]
                            initWithDelegate:self
                            delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    [sock connectToHost:@"localhost" onPort:kHKLDefaultListenPort+5 error:nil];

    // Wait a response from HKLSocketStubServer
    _sem_testResponse = dispatch_semaphore_create(0);
    long result = dispatch_semaphore_wait(_sem_testResponse,
                                          dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)));

    // Check the response
    XCTAssertEqual(result, 0, @"should get result immediately.");
    XCTAssertEqualObjects(@"bar", _str_response,
                          @"Received data should be [bar].");

    // Verify all responses have been sent.
    XCTAssertNoThrow([server verify], @"all fake responses have been sent.");

    _str_testRespondsResourceOfType = nil;
}

// GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    // Send "foo" data to server.
    NSData *data = [@"foo" dataUsingEncoding:NSUTF8StringEncoding];
    [sock readDataWithTimeout:-1 tag:0]; // Start reading without timeout
    [sock writeData:data withTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    // Store the received string(should be "bar") and signal to the main thread.
    _str_response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    dispatch_semaphore_signal(_sem_testResponse);
}
@end

Basics

Get a server instance and clear

Get shared instance.

HKLSocketStubServer *server =[HKLSocketStubServer sharedServer];

Remove all fake responses.

[server clear];

Expecations and verifycation

[[server expect] forData:[@"something binary data" dataUsingEncoding:NSUTF8StringEncoding]];

Register fake response. Server will response this fake if requested /fake. After this setup the functionality under test should be invoked followed by

[server verify];

When expected responses have not been invoked, verify method will raise an exception.

Stubs

[[server stub] forDataString:@"bar"]

stub is similar to expect, But stub remains server response queue after invoked it. Therefore, verify ignores response that registered by stub.

Complicated response

Simulate waiting

// e.g.) Send response after 10 sec.
[[[server stub] forDataString:@"heavy command"] andProcessingTime:10.0f];

Check incoming data in blocks

// e.g.) Log the data from client.
[[[stubServer expect] forData:data] andCheckData:^(NSData *data) {
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Received %@", str);
    }];

NLTHTTPStubServer architecture is also available for your understanding.

License

HKLSocketStubServer is available under the MIT license. See the LICENSE file for more info.

About

A fake TCP server for iOS testing, similar to NLTHTTPStubServer

Resources

License

Stars

Watchers

Forks

Packages