Sobes.tech
Junior — Middle

What is the main role and application of mock objects in testing?

sobes.tech AI

Answer from AI

Mock objects are used in testing to simulate the behavior of real system components with which the tested module interacts. The main role of a mock is to isolate the tested code from external dependencies (such as databases, network services) so that tests are fast, reliable, and reproducible.

Using mock objects allows:

  • To verify interactions with dependencies (e.g., method calls, transmitted parameters).
  • To simulate various scenarios of dependency operation (success, errors, delays).
  • To simplify the setup of the testing environment.

An example in Go using an interface and a mock for testing a function that calls an external service:

package service

type ExternalAPI interface {
    GetData(id string) (string, error)
}

func ProcessData(api ExternalAPI, id string) (string, error) {
    data, err := api.GetData(id)
    if err != nil {
        return "", err
    }
    return "Processed: " + data, nil
}

// Creating a mock in the test:

type MockAPI struct {}

func (m *MockAPI) GetData(id string) (string, error) {
    if id == "123" {
        return "mocked data", nil
    }
    return "", fmt.Errorf("not found")
}

// Test
func TestProcessData(t *testing.T) {
    mock := &MockAPI{}
    result, err := ProcessData(mock, "123")
    if err != nil || result != "Processed: mocked data" {
        t.Errorf("unexpected result: %v, error: %v", result, err)
    }
}
What is the main role and application of mock objects… - sobes.tech