GoLab 2018 - Adam Wolfe Gordon - Unit Testing Code with Hard-to-Mock Dependencies

Опубликовано: 26 Октябрь 2024
на канале: GoLab conference
685
15

Unit testing using mocks is a common technique in Go and other languages. However, some dependencies are harder to mock than others; standard library packages such os can be particularly tricky. This talk covers strategies for effectively testing code that depends on such hard-to-mock packages.

Mocking dependencies is a common unit testing technique. Mocks are code that can be injected in place of real dependencies, allowing a developer to control the behavior of these dependencies from a test. Mocks may be generated by a tool or written by hand, but either way they make it easy to exercise error conditions and isolate tests from external software and systems.

In Go, it’s easiest to use mocks for dependencies that export interfaces. A mock object conforming to some interface can be built or generated and injected for tests, while a real object conforming to the same interface is used in production. However, not all packages provide nice mockable interfaces. In particular, low-level packages such as the os package in the Go standard library tend to export functions (as opposed to structs with methods) and structs with data members (as opposed to accessor functions). These properties make it difficult to build mocks for testing code that depends on such packages.

This talk will provide a brief introduction to testing with mocks, discuss what makes some dependencies harder to mock than others, then describe strategies for testing code with hard-to-mock dependencies. Strategies include:
Isolating code that depends on hard-to-mock packages.
Wrapping hard-to-mock dependencies and using mocks.
Using function variables to mock exported functions without building unnecessary interfaces.
Composing wrapping, function variables, and mocks to simulate complex dependencies.

Attendees will learn about these strategies through a series of practical examples based on common Go use-cases. The examples will use programmable mocks generated with mockery and mockpkg, but the strategies are equally applicable to hand-built mocks or those generated by other tools.


💛 Follow us on TWITTER:   / golab_conf  
💜 Follow us on FACEBOOK:   / golabconf  

GoLab is the first Italian international conference on the Go programming language, organized by Develer.
Develer is not just an Italian company projecting and releasing hardware and software solutions for the industrial environment, but is also an ensemble of people sharing their great passion for new technologies and how they can be applied to your everyday life.

🔸 Follow DEVELER on INSTAGRAM:   / wearedeveler  
🔹 Follow DEVELER on FACEBOOK:   / we.are.develer  
🔸 Follow DEVELER on TWITTER:   / develer  
🔹 Follow DEVELER on LINKEDIN:   / 114426  
🔸 Follow DEVELER on TELEGRAM: https://t.me/wearedeveler
🔹 Follow DEVELER on TIK TOK:   / wearedeveler