Showing posts with label Testing. Show all posts
Showing posts with label Testing. Show all posts

Testing with Google Truth


wait(0) - Timed_Waiting vs Waiting: Troubleshooting Practice


Mockito Best Practices


Maven Tips and Tricks - 2016


Maven auto-completion
brew tap homebrew/completions

brew install maven-completion
Then add this to ~/.bash_profile:
if [ -f ~/.maven-completion.bash ]; then
  . ~/.maven-completion.bash
fi

Options
-U forces updates, force maven to download/re-download the dependencies
-o Offline
-q,--quiet Quiet output - only show errors

Skip Test
mvn install -DskipTests
This will skip compiling the test:
mvn install -Dmaven.test.skip=true

-DskipTests will compile test classes but not run them
-Dmaven.test.skip=true will skip compiling the tests

How maven resolve versions
Maven uses nearest wins strategy to determine dependency version.
mvn dependency:tree -Dverbose -Dincludes=com.amazonaws:aws-java-sdk-core
[INFO] |  \- com.amazonaws:aws-java-sdk-cloudfront:jar:1.11.32:compile

[INFO] |     \- (com.amazonaws:aws-java-sdk-core:jar:1.11.32:compile - omitted for conflict with 1.11.98)

mvn dependency:build-classpath

Purge dependencies that may be corrupted
mvn dependency:purge-local-repository

Download source jars from maven repository
-DdownloadSources=true -DdownloadJavadocs=true

Download all dependencies into target/dependencies
mvn dependency:copy-dependencies Check how libraries are imported
mvn dependency:tree
Check several specific libraries
mvn dependency:tree -Dverbose -Dincludes=log4j:log4j
Find out conflicted(multiple) version
mvn dependency:tree -Dverbose | grep 'omitted for conflict'

Use dependency:analyze to find out unused dependencies
Use maven-enforcer-plugin(DependencyConvergence) to prevent multiple versions of same library

Use scala-maven-plugin for mixed java/scala projects

Properties
<properties>
  <m2eclipse.wtp.contextRoot>your-app-name</m2eclipse.wtp.contextRoot>
</properties>

Testing
Run specific method
mvn test -Dtest=className#methodName

mvn exec:java -Dexec.mainClass=full.qualified.class -Dexec.classpathScope=test -Dexec.args=local

Testing with TestNG



Fail Fast Using TestListenerAdapter
Sometimes, we want to all suites stops immediately if one test fails, TestListenerAdapter can help on this. onTestFailure will be called when any test fails, it will set static boolean varible hasFailedTest to true.
public class MyTestNGListener extends TestListenerAdapter {
    private static boolean hasFailedTest;
    @Override
    public void beforeConfiguration(final ITestResult result) {
        if (hasFailedTest) {
            throw new SkipException("Skipping beforeConfiguration");
        }
        super.beforeConfiguration(result);
    }

    @Override
    public void onStart(final ITestContext testContext) {
        if (hasFailedTest) {
            throw new SkipException("Skipping onStart");
        }
        super.onStart(testContext);
    }

    @Override
    public void onTestStart(final ITestResult result) {
        if (hasFailedTest) {
            throw new SkipException("Skipping onTestStart");
        }
        super.onTestStart(result);
    }

    @Override
    public void onTestFailure(final ITestResult tr) {
        hasFailedTest = true;
    }
}

@Listeners({MyTestNGListener.class})
public abstract class BaseTest {}

@BeforeSuite + @BeforeClass
To test admin api which requires login first, we login in the @BeforeSuite and share the session in all test in the suite.
-- We use rest-assured to do end-2-end rest api testing.

To make the child class easier to use the sessionFilter, we use @BeforeClass to store it as instance variable.
public abstract class BaseTest {
  @BeforeSuite(alwaysRun = true)
  @Parameters({"adminBaseUrl", "clientBaseUrl", "username", "password"})
  public void setup(final String adminBaseUrl, final String username, final String password,
          final ITestContext context) {
      final SessionFilter sessionFilter = TestUtil.configureAdminRestAssured(adminBaseUrl, username, password);
      context.setAttribute(FILTER_NAME, sessionFilter);
  }

  protected RequestSpecification restRequestSpec, adminRequestSpec;
  protected SessionFilter sessionFilter;

  @BeforeClass(alwaysRun = true)
  @Parameters({"adminBaseUrl", "clientBaseUrl"})
  public void beforeClass(final String adminBaseUrl, final String clientBaseUrl, final ITestContext context) {
      restRequestSpec = new RequestSpecBuilder().setBaseUri(clientBaseUrl).setContentType(ContentType.JSON)
              .setRelaxedHTTPSValidation().build();

      adminRequestSpec = new RequestSpecBuilder().setBaseUri(adminBaseUrl).setContentType(ContentType.JSON)
              .setRelaxedHTTPSValidation().build();

      sessionFilter = (SessionFilter) context.getAttribute(FILTER_NAME);
  }
}

public static SessionFilter configureAdminRestAssured(final String baseUrl, final String username,
        final String password) {
    RestAssured.reset();
    RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
    RestAssured.config = config().logConfig(new LogConfig());
    RestAssured.config.getHttpClientConfig().reuseHttpClientInstance();
    RestAssured.config = config().sslConfig(sslConfig().allowAllHostnames());
    RestAssured.useRelaxedHTTPSValidation();
    
    final SessionFilter sessionFilter = new SessionFilter();
    final Map<string object> parameters = new HashMap<>();
    parameters.put("j_username", username);
    parameters.put("j_password", password);

    // if login successful, it will redirect it to index.html, check whether its status is 302,
    // the new location ends with index.html
    final ExtractableResponse<response> response =
            given().contentType(ContentType.URLENC).formParameters(parameters).filter(sessionFilter)
            .post(baseUrl + "/j_spring_security_check").then().statusCode(302).extract();
    assertThat(response.header("Location"), endsWith("index.html"));
    RestAssured.basePath = "/v1";
    return sessionFilter;
}


Spring Security: Integrate In-Memory Authentication for Test Automation


Use Case
To automate test of our web services apis, we need add test users in test environments.

The Solution
We configure Spring Security AuthenticationManager: first add  in-memory DaoAuthenticationProvider in test environments then add other authentication providers.

The legacy code uses xml to configure authenticationManager and intercept-url rules, so I create org.springframework.security.authenticationManager bean. If you are using pure java config, please check Spring Security Java Config.
@Configuration
public class WebSecurityConfiguration {
    private static final String[] ENV_SUPPORT_TEST_USER = {PROFILE_LOCAL, PROFILE_XX};

    @Autowired
    private Environment environment;

    @Bean(name = "org.springframework.security.authenticationManager")
    public AuthenticationManager authenticationManager() {
        final List providers = new ArrayList<>();

        final String env = System.getProperty("env");
        if (StringUtils.isBlank(env)) {
            throw new BusinessException(ErrorCode.INTERNAL_ERROR, "env is empty");
        }
        // The order matters: don't change the order - it will first try to use the test user
        // if not succeed then use ldap
        // add test user for local, q1, e1 only
        if (ArrayUtils.contains(ENV_SUPPORT_TEST_USER, env)) {
            addTestUserAuthProvider(providers);
        }

        if (PROFILE_LOCAL.equals(env) || PROFILE_DOCKER.equals(env)) {
            addLdapProviderForLocal(providers);
        } else {
            // application is deployed to aws, use different LdapAuthenticationProvider
            addLdapProviderForAwsEnv(providers);
        }

        final AuthenticationManager authenticationManager = new ProviderManager(providers);
        return authenticationManager;
    }

    protected void addTestUserAuthProvider(final List providers) {
        final DaoAuthenticationProvider testUserAuthProvider = new DaoAuthenticationProvider();
        final Collection users = new ArrayList<>();
        // add admin user
        UserDetails user = new User(environment.getProperty("spring.security.test.user.adminOnly.name"),
                environment.getProperty("spring.security.test.user.adminOnly.password"),
                Lists.newArrayList(new SimpleGrantedAuthority(environment.getProperty("spring.security.adminGroup"))));
        users.add(user);
        // add provisioner
        user = new User(environment.getProperty("spring.security.test.user.provisionerOnly.name"),
                environment.getProperty("spring.security.test.user.provisionerOnly.password"), Lists.newArrayList(
                        new SimpleGrantedAuthority(environment.getProperty("spring.security.provisionGroup"))));
        users.add(user);

        // add user with admin and provisioner
        user = new User(environment.getProperty("spring.security.test.user.adminProvisioner.name"),
                environment.getProperty("spring.security.test.user.adminProvisioner.password"),
                Lists.newArrayList(new SimpleGrantedAuthority(environment.getProperty("spring.security.adminGroup")),
                        new SimpleGrantedAuthority(environment.getProperty("spring.security.provisionGroup"))));
        users.add(user);

        final UserDetailsService userDetailsService = new InMemoryUserDetailsManager(users);
        testUserAuthProvider.setUserDetailsService(userDetailsService);

        providers.add(testUserAuthProvider);
    }
}

Testing with Rest-Assured
Now we can use Rest-Assured to login and capture the session and reuse it in subsequent requests.
RestAssured.reset();
RestAssured.baseURI = baseURI;
RestAssured.basePath = basePath;
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
RestAssured.config = config().logConfig(new LogConfig());
RestAssured.useRelaxedHTTPSValidation();

final SessionFilter sessionFilter = new SessionFilter();
given().auth()
.form(user, passwd,
        new FormAuthConfig("/j_spring_security_check", "j_username", "j_password"))
.filter(sessionFilter).expect().statusCode(200).when().get("/api");

// later...
given().filter(sessionFilter).contentType(ContentType.JSON).when().delete(productUrl).then()
        .statusCode(200);

Testing Tips for Java Developers


Mockito

doReturn|Answer|Throw()

reset

  • after reset
Mock chained calls
Do different things when call multiple times
Invalid use of argument matchers!
  • When using matchers, all arguments have to be provided by matchers.
UnfinishedVerificationException: Missing method call for verify(mock)
  • in verify, use any() for primitive arguments
Testing Servlet

Hamcrest

[TestNG]

Spring + JUnit

Using REST Assured to test http APIs

randomizedtesting


Eclipse

Plugins

  • MoreUnit
    • Ctrl+U: create test method
    • Ctrl+J: jump to test method

Add Static Import Automatically

  • To help write test cases easier, when we type “assertT” and hit Ctrl+Space, we want Eclipse to add static import automatically for us: import static org.hamcrest.MatcherAssert.assertThat;
  • Go to Window > Preferences > Java > Editor > Content Assist > Favorites, then add:

Run Tests across Multiple Projects

Create a maven project depending on all the projects you want to test.
Create Test code:

Maven

  • Run specific method: mvn test -Dtest=className#methodName

Misc

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)