Reputation: 125
I'm writing tests for a project of mine, which involves fixed filepaths and base URLs. To me, the most logic way to define them is by means of public/private constants in a relevant module, but that prevents good testing practices. How can I work around this?
I searched for a possible solution and found that I can define two constructors for a struct in need of a path: one which defines the default path, and another that accepts a custom path
func Construct(param string) MyStruct {
return MyStruct {Param: param, Path: "/default/path"}
}
func ConstructWithPath(param, path string) MyStruct {
return MyStruct {Param: param, Path: path}
}
This is pretty ugly to me and it's a solution tailored exclusively for tests since the paths I'm considering are fixed and known.
Upvotes: 2
Views: 1671
Reputation: 834
Your solution is fine. It's a common and recommended practice to design your code and interfaces to be testable. I would slightly modify your solution to prevent duplication-
func Construct(param string) MyStruct {
return ConstructWithPath(param, "/default/path")
}
func ConstructWithPath(param, path string) MyStruct {
return MyStruct {Param: param, Path: path}
}
You need not export ConstructWithPath if you don't want anyone outside this package using it.
Upvotes: 0
Reputation: 273796
This is known as dependency injection and is commonly used for testing. There's nothing particularly ugly about making your code more testable.
An alternative would be to define the paths as var
s in the package (make them private - tests live in the same package) and the tests could set these vars to something before doing the test.
Upvotes: 4