简体   繁体   中英

java junit testing in a loop

I have a JUnit test that I would like to run from a main method. I would like to retrieve multiple records from a database (within the main method) and pass each record into the JUnit, using a data object, so that each record can be tested. Can I pass a data object into the run method of JUnit. If not what is the best way to accomplish this. There are so many different scenarios that I would like to use actual data from the database. There could be as many as 5000 or more records to test.

Thanks Doug

You want to use JUnit's Parameterized Tests . There's really no way to run a main method in a JUnit test case.

On top of the docs, here's a blog post which explains it a little better: http://ourcraft.wordpress.com/2008/08/27/writing-a-parameterized-junit-test/

Surely you are looking for Parameterized test case. You can do it easily by using JUnit instead of using main() method.

You need Parameterized to run your test.

It will run your test with different parameters by passing parameters via constructor.

Here is an easy article how to do that. You can also try the example in the documentation also, to understand how it works.

I think that testing your main method is more along the lines of an integration test or a functional test. The same can be said for testing your database data. If you really want a unit test the firs step would be to refactor your main method using Extract Method to pull out the business logic you want to test.

Doing this gives you a few benefits. First can test your code in isolation (which is one of the more important properties of a good unit test). If you refactor out the business logic you'll know that you are only testing that code and that no other code is affecting your test. Second by having an isolated method you'll be able to easily mock the test data you are looking at by passing in different parameters to the method and make your assertions based on the known mock data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM