Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

behavior
module
elixir

What are behaviours and why are they important in testing?

Mahnoor Fatima

Behaviors in Elixir are the interfaces that are in Object-Oriented Programming. They provide an abstract definition of a module for testing. A behavior typically consists of a set of functions that need to be implemented by the module.

Behaviours ensure that:

  • The functions that need to be implemented are defined within the behavior.
  • The functions are implemented in the actual module.

In case the function inside a behavior is not implemented, :error is raised.

Example

For instance, we can ensure that certain modules parse strings. For this, we can introduce a Parse behavior, such as the example below:

defmodule @Parse do
    @doc '''
    Parse a string
    '''
    @callback parse(String.t) :: {:ok, term} | {:error, String.t}
end
  

Now this behavior is implemented in a module:

defmodule JSONParser do
  @behaviour Parse

  @impl Parse
  def parse(str), do: {:ok, "some json " <> str} # ... parse JSON
end

Explanation

Asserting that the module JSONParser has behavior Parse, we can ensure that the function parse() returns a string. The absence of the function or the wrong return type would have raised an error.

RELATED TAGS

behavior
module
elixir

CONTRIBUTOR

Mahnoor Fatima
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring