Home > Backend Development > Golang > 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
Release: 2024-02-06 08:45:03
forward
736 people have browsed it

是否可以在 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},
}
Copy after login

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!

source:stackoverflow.com
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