How to skip code section when unittesting in java

I am working on a Java web application with unit / integration tests. The application is deployed to Jetty and uses H2 db when starting the maven integration testing phase. I have one oracle function that is called from the dao level, which cannot be ported to H2 db, so I want to mock this part of the code while running the test cases.

I was thinking about having a flag that can determine if I am running in the application in test mode and set a condition for it in the code, but for me it does not look like. Please suggest a better approach to achieve this.

+4
source share
3 answers

Extract your own Oracle call to a separate class (maybe some DAO). Add this DAO to the class that uses it. Create a second implementation of this DAO, doing nothing instead of calling Oracle. During integration testing, implement the latest implementation.

Avoid flags in code. If you use Spring, use assembly profiles that will selectively create one implementation or another.

How dependency injection helps you test your code: if you want to mock some part of the system, just enter the mock version.

+3
source

Please use some nice mocking frameworks like mockito or jMock or some other similar frameworks.

Please note: you may need a code refactor to make it more verifiable.

+1
source

If the question is really this:

How to skip code section when deleting in java

then I agree with the answers. Inclusion of dependencies, mocking frameworks - this is absolutely the right way to conduct true unit testing.

However, if the question is:

How to skip a section of code when using JUnit (or another unit testing framework)

Then I think the answer is "it depends." Sometimes I use JUnit to test integration - fragments of client code that I run on a test server to save me from having to run these tests on the client side manually through a graphical interface. In this case, I use system properties, for example, in my base class:

protected boolean skipTest() { String port = System.getProperty("jersey.test.port"); // don't run this test unless developer has explicitly set the testing properties // this is an integration test, not a unit test return port == null; } 

Then in the actual test class it looks like this:

 // verify a successful login @Test public void testLogin() { if (skipTest()) return; // do real test 

So, I thought that if you really cannot reorganize the Oracle material from your DAO, then you really do an integration test, and it is ok to have skipTest in the unit test.

+1
source

Source: https://habr.com/ru/post/1437889/


All Articles