Home  >  Article  >  Backend Development  >  How to call "assert" function from non-test function?

How to call "assert" function from non-test function?

WBOY
WBOYforward
2024-02-10 10:30:10493browse

How to call assert function from non-test function?

php editor Strawberry brings you an article on how to call the "assert" function from a non-test function. In PHP, we usually use "assert" function for writing test cases, but sometimes we want to use it in non-test functions as well. This article will introduce in detail the steps and precautions on how to call the "assert" function in non-test functions to help readers better understand and use this function. Whether you are a beginner or an experienced developer, you will gain valuable knowledge and tips from this article. Let’s explore together!

Question content

This question is similar to assertions in non-test functions in Go, but I do want to call assert.ElementsMatch from the non-test function.

How to instantiate the testing.T object?

This function will eventually be called from main, which is configured with flags, so it can't just be a test.

Context: We are performing data migration from some source database to target database. The first part of the migration is to copy the data from the source to the target's save table. The second part (and this is where assert.ElementsMatch comes into play) is to see how the saved table differs from the generic table - we want to try to catch unforeseen situations with data migration (e.g. the formatting of certain dates May be different or wrong) ID number has been copied). The third part is, once the save table data has been reviewed, copy it into the generic table. This all sounds a bit overly complex, but that's probably because you're currently using a source database and a target universal database.

Workaround

You don't need an instance of testing.T.

The

assert.ElementsMatch function takes as its argument assert.TestingT, which is an interface with a single method. So you can simply define a custom implementation of the interface that can do whatever you like using the method, and pass an instance of that custom implementation to assert.ElementsMatch.

For example:

type testingT struct{}

func (testingT) Errorf(format string, args ...interface{}) {
    fmt.Printf(format, args...)
}

// ...

t := new(testingT)
if assert.ElementsMatch(t, listA, listB) {
    // ...
}

The above is the detailed content of How to call "assert" function from non-test function?. 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