Our Blog.

Expert thoughts from our software developers and design leaders.

  • Manuel Perez on October 10, 2019

    How to mock an external service for tests in GO

    From my experience as a software developer, an issue that I have dealt when building an application are the dependencies for external services. A test with external dependencies where you don’t have much control can fail if there is a change in the service and the outcome is not the expected, with this in mind, we need to ensure the non-dependence of external services when running our tests. The most effective way to do this is mocking those dependencies.

    In this post, I will focus on the functional tests of an application. I will also talk about how to mock an external service to not rely on it when running our functional tests.

    To explain how to mock an external service, I’ll walk you step by step through an example.

    Let’s say that we have an endpoint, that is using a third-party package called holidays that is making HTTP requests to an external service to get such holidays.

    # /actions/holidays.go
    package actions
    
    import (
        "time"
        "github.com/somebody/holidays"
        "github.com/somebody/holidays/filters"
    )
    
    func Holidays(w http.ResponseWriter, r *http.Request) {
        currentMonth := int(time.Now().Month())
    
        filters := filters.Params{
            Months: []int{currentMonth}
        }
        
        message := "There are not holidays"
        
        days, _ := holidays.GetHolidays(filters)
        if len(days) > 0 {
            message = fmt.Sprintf("Holidays for this month: %v", days)
        }
    
        fmt.Fprintf(w, message)
    }
    

    Step 1: Separating the external service logic from our business logic.

    The environment where we executed the tests should not depend on any external service. Since we’re only testing the functionalities of our application and how it behaves with any input, regarding external services, we only care about the outcome of it.

    To achieve a higher level of control over our tests, we need to move all the holidays-service-logic to a separate package.

    # /lib/holidays/holidays.go
    package holidays
    
    import (
        "github.com/somebody/holidays"
        "github.com/somebody/holidays/filters"
    )
    
    func Holidays(months []int) ([]int, error) {
        filters := filters.Params{
            Months: months
        }
        days, err := holidays.GetHolidays(filters)
    
        return days, err
    }
    

    Once the logic is separated we have to make sure we must call the external service using the new package from our actions package.

    # /actions/holidays.go
    import (
        "project/lib/holidays"
    )
    
    func Holidays(w http.ResponseWriter, r *http.Request) {
        ...
        days, _ := holidays.Holidays(months)
        ...
    }
    

    Step 2: Abstracting the use of the service through an interface.

    So far, this solution doesn’t solve the problem, the tests are still executing all the holidays-service-logic so we are still making HTTP requests that we don’t want to be made. We have to do something else.

    To mock the external service, we can abstract all its logic within an interface which we can implement elsewhere and use it by our functional tests, returning the outcome we need to test the behavior of our application.

    Here is how such an interface would look like:

    # /lib/holidays/holidays.go
    package holidays
    
    import (
        "github.com/somebody/holidays"
        "github.com/somebody/holidays/filters"
    )
    
    var Client ServiceFunctions = holidaysService{}
    
    type ServiceFunctions interface {
        Holidays([]int) ([]int, error)
    }
    
    type holidaysService struct{}
    
    func (hs holidaysService) Holidays(months []int) ([]int, error) {
        filters := filters.Params{
            Months: months
        }
        days, err := holidays.GetHolidays(filters)
        return days, err
    }
    

    Client is a global variable that receives as value any type that implements the ServiceFunctions interface, by default it uses holidaysService{} who communicate with the external service but on the side of the tests, we can update its value with another type that implements the same interface by returning the outcome we want.

    var Client ServiceFunctions = holidaysService{}
    

    We have to make a change in the way of calling the external service, now it would be through our Client global variable.

    # /actions/holidays.go
    
    func Holidays(w http.ResponseWriter, r *http.Request) {
        ...
        days, _ := holidays.Client.Holidays(months)
        ...
    }
    

    Step 3: Create the mock of our interface.

    Once all the functions of the holidays-service are abstracted, we need to create another type that implements the same interface with the intent to use it as a dummy object for our tests. In this case, our new Holidays function we’ll return a list of hard-coded days and an error.

    # /lib/holidays/holidays_mock.go
    package holidays
    
    var (
        Days []int{}
        HolidaysError error
    )
    
    type ServiceFuncMock struct{}
    
    func (sfm ServiceFuncMock) Holidays(months []int) ([]int, error) {
        return Days, HolidaysError
    }
    

    We can make this interface as dynamic as we want, we can return different values in order to test how our application behaves.

    Step 4: How to use the mock?

    Given our test is still depending on external service. We will replace the holidays-service call by the simulation we created.

    We assign an instance from our mock to the Client variable we defined before:

    holidays.Client = holidays.ServiceFuncMock{}
    

    Here we are setting the value for our Client, we’re using the ServiceFuncMock "test interface" as the default interface.

    Here is an example of how to test our application with no external dependencies.

    Test 1: In this test, we simulate the response from the holiday-service with an empty list of holidays and our application should display “There are not holidays”.

    # /actions/holidays_test.go
    package actions
    
    import (
        ...
        "project/lib/holidays"
    )
    
    func Test_Holidays_Without_Days(t *testing.T) {
        holidays.Client = holidays.ServiceFuncMock{}
    
        req, _ := http.NewRequest("GET", "/holidays", nil)
        ...
    
        assert.Contains(t, res.Body.String(), "There are not holidays")
    }
    

    Test 2: In this case, we set a different response for the days that the Holidays function will return.

    # /actions/holidays_test.go
    
    ...
    
    func Test_Holidays_With_Days(t *testing.T) {
        holidays.Client = holidays.ServiceFuncMock{}
        holidays.Days = []int{1, 3, 5}
    
        req, _ := http.NewRequest("GET", "/holidays", nil)
        ...
    
        assert.Contains(t, res.Body.String(), "holidays for this month")
        assert.Contains(t, res.Body.String(), "1")
        assert.Contains(t, res.Body.String(), "3")
        assert.Contains(t, res.Body.String(), "5")
    }
    

    As you can see, mocking external services is an effective method when testing our application’s features that require the use of them. This method also serves us well to decrease the coupling of our application regarding external services.

    Thanks a lot for reading! Keep on learning and coding!

    Continue Reading
  • Efren Ospino on October 3, 2019

    How's it like to write an Android app in 2019?

    First, for Java developers only

    As Android developers, there are many ways to write an app and get tired of seeing how the lack of features of the Java (Java6 by default) platform embedded in the Android SDK slows the coding process. Notice that Java6 last public update dates from 2013 and that is the version you are expected to use on Android development with Java. You can use Java8 language features but most of the powerful features can only be used in devices that are running Android 7.0 Nougat (API 24).

    By May 7, 2019, Android 10 not released yet, there was a total close to 41.9% devices running Android OS prior Nougat out of 2.5 billion active devices.

    alt text

    This means that all of those devices are not able to take advantage of most of the Java8 features like functional interfaces, Stream API, Concurrency and IO enhancements and more. And without mentioning any of the post Java8 releases (Java13 is already here).

    Hello Kotlin

    JetBrains, the company that develops IntelliJ IDEA (a powerful Java IDE and what Android Studio is based on), back in 2011 began developing Kotlin, a new cross-platform, general-purpose programming language that interoperates with Java and the JVM. They addressed some issues that the Java Programming Language has and made a good job of giving Kotlin the ability to run well enough to develop Android applications. This huge effort won some interest in the community and within the Android development team making it a topic of conversation between Android developers a few years ago.

    People got started with Kotlin by writing new features and apps from scratch using a couple of Gradle plugins that JetBrains developed but there was no official support from the Android team at Google. At I/O 2017, it was announced that Kotlin was going to be a first-class language for Android development together with Java and C++. They were not replacing anything at this point but it was a big step the fact that a new language has been added officially and allowed developers to write Kotlin code in Android Studio IDE in the easiest way.

    2 years later, at I/O 2019, it was announced Kotlin at their most preferred language inside the Android team which meant they will opt the Kotlin-first approach and all the new Android platform support features were going to be developed thinking in Kotlin developers. This way Google has reinforced their support for Kotlin and encouraged developers to write more applications using Kotlin.

    Nowadays, most of the Android developer documentation by Google is offered in Kotlin with code examples. New support libraries, Android KTX and more libraries are being released as well in Kotlin. Apps and Open Source libraries are written in Kotlin more and more, and the community has accepted their use.

    You may ask, what’s next?

    Besides the Java Programming Language is a powerful language and there is no doubt about it, excellent apps can be written by using it as the main language on your Android project but you should get started with Kotlin. It is a modern programming language and it has features that you will want to appreciate when writing your Android app. Today, there is the chance to work with it and it is not a bad idea to start playing with it.

    At Wawandco we love Kotlin! And it has been a nice ride since we started using it the last year. We became more productive and we did learn it fast. We encourage you to learn Kotlin if you haven’t already! There are many advantages that you win by using this programming language and it is worthy of giving it a try.

    Continue Reading