Home  >  Article  >  Backend Development  >  Is it possible to define different return types in Go unit tests

Is it possible to define different return types in Go unit tests

WBOY
WBOYforward
2024-02-06 08:45:03698browse

是否可以在 Go 单元测试中定义不同的返回类型

Question content

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


Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete