Home > Backend Development > Golang > How Can You Redefine Constants in Go for Testing?

How Can You Redefine Constants in Go for Testing?

DDD
Release: 2024-11-02 11:49:02
Original
816 people have browsed it

How Can You Redefine Constants in Go for Testing?

Redefining Constants for Testing in Go

In production code, it's often desirable to use constants for stable values like base URLs. However, this can pose challenges when testing, as the default implementation of const in Go does not allow reassignment.

Problem:

Consider the following code snippet, which tries to redefine the baseUrl constant in the test file:

<code class="go">package main

const baseUrl = "http://google.com"

// in main_test.go
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  ...
 }
const baseUrl = ts.URL // throws error: const baseUrl already defined</code>
Copy after login

This code will fail with the error const baseUrl already defined, as Go doesn't allow redefining constants.

Solution:

To enable testing-friendly constants, consider refactoring your code. Instead of using a global constant, create a function that takes the constant value as a parameter:

<code class="go">const baseUrl_ = "http://google.com"

func MyFunc(baseUrl string) {
    // Use baseUrl
}</code>
Copy after login

In the test file, you can redefine the baseUrl parameter without affecting the production code:

<code class="go">// in main_test.go
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  ...
 }
myFuncImpl(ts.URL) // Call the function with the test URL</code>
Copy after login

This approach allows you to test your code with different values of the constant while preserving the original implementation. The original function MyFunc() still uses the production-constant value, ensuring stability for non-testing scenarios.

The above is the detailed content of How Can You Redefine Constants in Go for Testing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template