Showing posts with label Testing. Show all posts
Showing posts with label Testing. Show all posts
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
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.
@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.
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;
}
Labels:
Testing
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.
Testing with Rest-Assured
Now we can use Rest-Assured to login and capture the session and reuse it in subsequent requests.
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
- Don’t mock too much, only mock directly dependence
- Steps: create mock:@Mock -> stubbing:when/thenReturn -> Verify: verify
- @Spy: used to wrap a real object. Every call, unless specified otherwise, is delegated to the object.
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
// When can't use @RunWith, for example test class already extends another base class.
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
// Annotations
@Mock
Mockito.mock(XX.class) // or
@Spy
@InjectMocks
@Captor
ArgumentCaptor<XClass> captor=ArgumentCaptor.forClass(XClass.class);
verify(mock).doSomething(capto.capture());
// Stubbing
when(mockObj.someMethod(0)).thenReturn("someThing");
when(mockObj.someMethod(1)).thenThrow(new RuntimeException());
when(instance.someMethod()).thenReturn(someValue);
thenThrow(Throwable)
thenCallRealMethod()doReturn|Answer|Throw()
- Important gotcha on spying real objects!
- use doReturn|Answer|Throw() to stub spy object
- use doXXX on void methods
// spy instance field
Typex ox = Mockito.spy(anObject.aField);
anObject.aField = ox;
doReturn("some").when(spyObj).someMethod();
doCallRealMethod().when(instance).voidMethod();
doThrow(new Exception()).when(instance).voidMethod()
verify(mockObj, never()).someMethod(param);
verifyZeroInteractions(mock...);
verify(mockObj, atLeast(2)).someMethod();
verify(mockObj, times(3)).someMethod();reset
- after reset
Mock chained calls
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
SomeService service;
when(service.getX().getY()).thenReturn(Z);Do different things when call multiple times
Invalid use of argument matchers!
- When using matchers, all arguments have to be provided by matchers.
//incorrect:
someMethod(anyObject(), "raw String");
// Should be
someMethod(anyObject(), eq("raw String"));UnfinishedVerificationException: Missing method call for verify(mock)
- in verify, use any() for primitive arguments
Testing Servlet
when(request.getParameter("user")).thenReturn("userA");
verify(response).setContentType("plain/text");
verify(response).addHeader("headerA")).thenReturn("value");Hamcrest
- More Readable.
- Provides Better Failure Messages
- Type Safety
- hasItem, contains, containsInAnyOrder
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
org.hamcrest.Matchers
containsString, startsWith, endsWith, equalTo,equalToIgnoringCase, equalToIgnoringWhitespace, isEmpty, isEmptyOrNull and stringContainsInOrder
assertThat(actual, containsString(expected));
assertThat(actual, nullValue());
assertThat(actual, notNullValue());
assertThat(subClass, instanceOf(BaseClass.class));[TestNG]
Spring + JUnit
Using REST Assured to test http APIs
Response rsp = given().filter(sessionFilter).when().get(someUrl).then().statusCode(is(200))).extract().response()
Map importResult = rsp.as(Map[].class)[0];
assertThat(Boolean.valueOf(importResult.get("success").toString()), is(true));randomizedtesting
@RunWith(RandomizedRunner.class)
@Seed("the-seed")
@com.carrotsearch.randomizedtesting.annotations.Repeat(iterations = 5)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:
org.hamcrest
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*
org.mockito.Mockito
org.mockito.Matchers
org.mockito.ArgumentMatchers
io.restassured.RestAssuredRun Tests across Multiple Projects
Create a maven project depending on all the projects you want to test.
Create Test code:
import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;
@RunWith(ClasspathSuite.class)
public class TestRunner {
}Maven
- Run specific method: mvn test -Dtest=className#methodName
Misc
- json-server - Get a full fake REST API Server
- Loading test
- JMeter
- Tsung
- locustio
Subscribe to:
Posts (Atom)
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)