Unit Test and Integration Test using Maven+JUnit4

Unit Testing

Unit testing is the practice of testing small pieces of code, typically individual functions, alone and isolated. Unit testing is the backbone. You can use unit tests to help design your code and keep it as a safety net when doing changes. Unit tests are also great for preventing regressions

Integration Testing

In integration testing, the idea is to test how parts of the system work together – the integration of the parts. Integration tests are similar to unit tests, but there’s one big difference: while unit tests are isolated from other components, integration tests are not.

Functional Testing

Functional testing is also sometimes called E2E testing, or browser testing. They all refer to the same thing.
Functional testing is defined as the testing of the complete functionality of some application. In practice with web apps, this means using some tool to automate a browser, which is then used to click around on the pages to test the application.

Using JUnit Categories and Maven to Split Unit Testing and Integration Testing

Define A Marker Interface

The first step in grouping a test using categories is to create a marker interface.
This interface will be used to mark all of the tests that you want to be run as integration tests.

public interface IntegrationTest {}

Mark your test classes

Add the category annotation to the top of your test class. It takes the name of your new interface.

import org.junit.experimental.categories.Category;
@Category(IntegrationTest.class)
public class ExampleIntegrationTest{
  @Test
  public void longRunningServiceTest() throws Exception {
  }
}

Configure Maven Unit Tests

The beauty of this solution is that nothing really changes for the unit test side of things.
We simply add some configuration to the maven surefire plugin to make it to ignore any integration tests.


  org.apache.maven.plugins
  maven-surefire-plugin
  2.11
  
   
     org.apache.maven.surefire
     surefire-junit47
     2.12
   
  
  
    
      **/*.class
    
    com.test.annotation.type.IntegrationTest
  

When you do a mvn clean test only your unmarked unit tests will run.

Configure Maven Integration Tests

Again the configuration for this is very simple.
To run only the integration tests, use this:


  org.apache.maven.plugins
  maven-surefire-plugin
  2.11
  
   
     org.apache.maven.surefire
     surefire-junit47
     2.12
   
  
  
    com.test.annotation.type.IntegrationTest
  

If you wrap this in a profile with id IT, you can run only the fast tests using mvn clean install. To run just the integration/slow tests, use mvn clean install -P IT.

Reference

  1. https://stackoverflow.com/questions/2606572/junit-splitting-integration-test-and-unit-tests/10381662#10381662
  2. https://codeutopia.net/blog/2015/04/11/what-are-unit-testing-integration-testing-and-functional-testing/

你可能感兴趣的:(Unit Test and Integration Test using Maven+JUnit4)