Home >Backend Development >Golang >Is it possible to define different return types in Go unit tests
I'm trying to implement unit testing for a Go client. Can I leave want
in the unit test to infer the type?
var halfTests = []struct { in int want type1 | type2 }{ {1, type1}, {3, type2}, }
I checked this: Options for different return types based on parameters
If it is difficult to test, it may indicate a design issue with the test or code . Ask yourself why this unit of code can produce two different types of output in the same test. Maybe your "unit test" tests too many at once. Perhaps the device's interface could be redesigned.
If you decide yes, then you should indeed look like this, defining an interface with common methods of type1 and type2 that you want callers to use.
If there is no common interface, question the design of the test and the unit being tested again; why does one unit return two unrelated types?
If you still feel it is necessary, use interface {}
. The caller must use a type switch to check the type. See Interfaces in Golang.
The above is the detailed content of Is it possible to define different return types in Go unit tests. For more information, please follow other related articles on the PHP Chinese website!