Golang模拟上下文恐慌

时间:2020-07-02 11:52:18

标签: unit-testing go mockery testify

因此,我正在使用mockerytestify在golang中进行单元测试

测试代码如下:

const bufSize = 1024 * 1024

var lis *bufconn.Listener

var mockAccountService = &mocks.AccountService{}

func init() {
    lis = bufconn.Listen(bufSize)
    s := grpc.NewServer()
    RegisterAccountManagementHandlerServer(s, &server{mockAccountService})
    go func() {
        if err := s.Serve(lis); err != nil {
            log.Fatalf("Server exited with error: %v", err)
        }
    }()
}

func bufDialer(context.Context, string) (net.Conn, error) {
    return lis.Dial()
}

func TestSayHello(t *testing.T) {

    var a uint64 = 1

    ctx := context.Background()

    conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
    if err != nil {
        t.Fatalf("Failed to dial bufnet: %v", err)
    }
    defer conn.Close()
    client := NewAccountManagementHandlerClient(conn)

    mockAccountService.On("GetSavingAccount", context.Background(), a, a, "Hello", 1).Return(&models.SavingAccount{
        CustomerID:      1,
        ID:              1,
        CardNo:          "Hello",
        SavingProductID: 1,
        Balance:         0,
        Status:          1,
    })

    resp, err := client.GetSavingAccount(ctx, &GetSavingAccountDataRequest{
        Id:              1,
        CustomerId:      1,
        CardNo:          "Hello",
        SavingProductId: 1,
    })

    if err != nil {
        t.Fatalf("SayHello failed: %v", err)
    }
    fmt.Printf("Response: %+v", resp)
    // Test for output here.

但是我得到这样的错误:


panic: 

mock: Unexpected Method Call
-----------------------------

GetSavingAccount(*context.valueCtx,uint64,uint64,string,int64)
                0: &context.valueCtx{Context:(*context.valueCtx)(0xc000115260), key:grpc.streamKey{}, val:(*transport.Stream)(0xc0004a2200)}
                1: 0x1
                2: 0x1
                3: "Hello"
                4: 1

The closest call I have is: 

GetSavingAccount(mock.AnythingOfTypeArgument,uint64,uint64,string,int)
                0: "&context.ValueCtx"
                1: 0x1
                2: 0x1
                3: "Hello"
                4: 1

我应该为模拟context.Background()传递什么值?

我尝试了mock.AnythingOfType("&context.emptyCtx")mock.Anything无效

谢谢

编辑:

我尝试过

mockAccountService.On("GetSavingAccount", context.Background(), a, a, "Hello", 1).Return(...})

并获得:

GetSavingAccount(*context.valueCtx,uint64,uint64,string,int64)
                0: &context.valueCtx{Context:(*context.valueCtx)(0xc000021290), key:grpc.streamKey{}, val:(*transport.Stream)(0xc000522100)}
                ...
The closest call I have is: 

GetSavingAccount(*context.emptyCtx,uint64,uint64,string,int)
                0: (*context.emptyCtx)(0xc00002a080)
                ...

GetSavingAccount方法的方法定义为:

func (a *accountService) GetSavingAccount(ctx context.Context, customerID, id uint64, cardNo string, savingProductId int64) (*models.SavingAccount, error)

1 个答案:

答案 0 :(得分:2)

所以,您有方法:

@Configuration
@EnableTransactionManagement
@PropertySource({"classpath:dao.properties"})
@EnableJpaRepositories(basePackages = {"com.university.dao"})
public class ApplicationConfig {

    @Autowired
    private Environment environment;

    public ApplicationConfig() {
        super();
    }

    @Bean
    public DataSource dataSource() {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(Preconditions.checkNotNull(environment.getProperty("jdbc.driverClassName")));
        dataSource.setUrl(Preconditions.checkNotNull(environment.getProperty("jdbc.url")));
        dataSource.setUsername(Preconditions.checkNotNull(environment.getProperty("jdbc.user")));
        dataSource.setPassword(Preconditions.checkNotNull(environment.getProperty("jdbc.password")));

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
                                                                       Environment environment) {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setDataSource(dataSource);
        entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactory.setJpaProperties(getHibernateProperties());
        entityManagerFactory.setPackagesToScan("com.university.domain");

        return entityManagerFactory;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory(dataSource(),environment).getObject());

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    final Properties getHibernateProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("hibernate.hbm2ddl.auto"));
        hibernateProperties.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect"));
        hibernateProperties.setProperty("hibernate.show_sql", environment.getProperty("hibernate.show_sql"));
        hibernateProperties.setProperty("hibernate.format_sql", environment.getProperty("hibernate.format_sql"));
        hibernateProperties.setProperty("hibernate.ejb.naming_strategy", environment.getProperty("hibernate.ejb.naming_strategy"));

        return hibernateProperties;
    }
}

你嘲笑了

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>university</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.reporting.outputEncoding>UTF-8</project.build.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit-jupiter.version>5.6.1</junit-jupiter.version>
        <junit.version>4.13</junit.version>
        <org.springframework.version>5.2.7.RELEASE</org.springframework.version>
        <org.springframework.boot.version>2.3.1.RELEASE</org.springframework.boot.version>
        <org.hibernate.validator.version>6.1.5.Final</org.hibernate.validator.version>
        <org.apache.tomcat.version>9.0.36</org.apache.tomcat.version>
        <com.vaadin.version>16.0.0</com.vaadin.version>
        <org.junit.jupiter.version>5.6.2</org.junit.jupiter.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>3.0.0-M1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.university.Main</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${org.springframework.boot.version}</version>
            </plugin>
            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${com.vaadin.version}</version>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${com.vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>${org.springframework.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>${org.springframework.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${org.springframework.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${org.springframework.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${org.hibernate.validator.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-dbcp</artifactId>
            <version>${org.apache.tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring-boot-starter</artifactId>
            <version>${com.vaadin.version}</version>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin</artifactId>
            <version>${com.vaadin.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>29.0-jre</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.12.jre7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.200</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${org.junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${org.junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <version>${org.junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.stefanbirkner</groupId>
            <artifactId>system-rules</artifactId>
            <version>1.19.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-reflect</artifactId>
            <version>2.0.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

您在最后一个参数上有所不同,您的问题是 int64 int ,因此您需要:

GetSavingAccount(*context.Context,uint64,uint64,string,int64)

对于上下文参数总是使用模拟。任何东西,比模拟上下文更容易。注意int / int64 / int32和其他类型,以及指针/结构参数。

相关问题