Rectangle 27 6

I think that Andrey's answer cannot help. He quotes that each request will use the same cookies BUT according to jmeter manual:

As far as I understand the question, you want each thread to share the same session ID cookie. So it seems to me you need to have two thread groups and execute them consecutively. First thread group (with a single thread that executes once only) should login and save the session cookie value to a global parameter (perhaps you need to use jmeter's scripting capabilities). Then set that cookie in the cookie manager of the second thread group.

java - Session/cookie management in Apache JMeter - Stack Overflow

java session cookies jmeter session-cookies
Rectangle 27 109

School 2.5 - Failsafe with the test cases starting their own Tomcat7 s...

There are a number of schools of thought as to how to handle this type of integration test with Maven.

I should point out that when you are deploying an application to an application server, you are not in the realm of unit testing any more. Because the entire application is being deployed within a container, you are testing the integration of those two components.

Now there is nothing wrong with using JUnit for running integration tests (though there are some limitations that you may hit, for example unit tests should not care about the sequencing of individual tests - assuming you are writing them correctly - so JUnit enforces this by not guaranteeing any sequence of execution... prior to Java 1.7 the execution order was accidentally implied by the order of test methods within a class, but it was not part of the JUnit contract... Some people switch to other testing frameworks for their integration tests, e.g. TestNG, if they find the unit test focus of JUnit is getting in the way of their test development)

The key point to keep in mind is that the Maven lifecycle uses the test phase for the execution of unit tests.

When it comes to integration tests there are two (and a half) schools of thought as to the right way to handle the tests with Maven.

This school of thought uses the phases after package to start up a container, run the integration tests, tear down the container, and finally check the test results and fail the build in the event of test failures.

mvn integration-test
mvn verify

So with this you do the following:

pre-integration-test
fork
=true
integration-test
post-integration-test
verify

For extra brownie points you would use build-helper-maven-plugin:reserve-network-port bound to the validate phase to ensure that the test server is started on an unused network port and then either use resource filtering against the test resources to pass the port through to the tests or use a system property passed through systemPropertyVariables to make the port number available to the tests.

  • If the tests fail, you cannot release the project
  • Can move the integration tests into a separate profile (by convention called run-its) if the tests are too slow to run every build.
  • Hard to run the tests from an IDE. All the integration tests start/end in IT and while Maven knows to run tests starting/ending in Test with Surefire and run tests starting/ending in IT with Failsafe, your IDE probably doesn't. Additionally, your IDE is not going to start the container for you, so you have to do a lot of work by hand to actually run the tests manually.

Debugging the tests potentially requires attaching two debuggers, e.g. one to debug the application running in container and the other to debug the test cases.

mvnDebug -Dmaven.failsafe.debug=true verify

This school of thought moves the integration tests into a separate module that depends on the war module and copies the war into the test resources using, e.g. dependency:copy-dependencies bound to the generate-test-resources phase coupled with a Tomcat7 dependency to test against.

The test cases themselves start up the Tomcat7 container using embedded mode

  • Tests can run in IDE
  • Integration tests are separated from Unit tests, so asking the IDE to run all tests will not kick off the slower tests
  • The war artifact is only rebuilt if you go past the package phase, consequently, you need to run at least mvn clean package periodically to refresh the code under test when using the IDE.
  • The failure of the integration tests does not break the build of the war module, so you can end up releasing a broken war artifact and then have the reactor build fail for the integration test module. Some people counteract this issue by having the integration test module within src/it and using Maven Invoker Plugin to run the tests... though that provides a poorer IDE integration, so I do not recommend that line.
  • Hard to get a consolidated test coverage report from Maven.

This is a kind of hybrid of the two approaches.

You use Failsafe to execute the tests, but the tests themselves are responsible for starting and stopping the Tomcat7 container that you want to test in.

  • Don't have to configure the server start/stop in Maven pom
  • IDE can safely run all tests (though the integration tests may be slower and you may want to not run them, but it's not like they will all fail unless there is a test failure)
  • Easier to debug the tests from your IDE (only one process to attach against, and the IDE usually makes it easy to debug tests by providing a special test runner)
  • Have to code the container start/stop yourself from within your test cases

I hope the above helps you understand the options you have. There may be other tweaks but in general the above are considered the best practice(s) for integration testing with Maven at present.

+1 One of the best answers on SO I have seen in a while.

I really like your response. There's just one thing that I'm fuzzy on: where did you figure out the convention of naming the profile that'll run integration tests "run-its"?

Lots of projects use that profile name, so it has become the convention... Especially as it is the convention we use in the maven project itself

Failsafe and integration-test/verify plus Eclipse: in our case, we generally run our app servers locally from Eclipse, and use the annotation @RunWith(SpringJUnit4ClassRunner.class) on our integration tests, which seems to be enough for Eclipse to recognise our unit tests.

Maven - deploy webapp to tomcat before JUnit test - Stack Overflow

maven tomcat junit maven-2 tomcat7
Rectangle 27 109

School 2.5 - Failsafe with the test cases starting their own Tomcat7 s...

There are a number of schools of thought as to how to handle this type of integration test with Maven.

I should point out that when you are deploying an application to an application server, you are not in the realm of unit testing any more. Because the entire application is being deployed within a container, you are testing the integration of those two components.

Now there is nothing wrong with using JUnit for running integration tests (though there are some limitations that you may hit, for example unit tests should not care about the sequencing of individual tests - assuming you are writing them correctly - so JUnit enforces this by not guaranteeing any sequence of execution... prior to Java 1.7 the execution order was accidentally implied by the order of test methods within a class, but it was not part of the JUnit contract... Some people switch to other testing frameworks for their integration tests, e.g. TestNG, if they find the unit test focus of JUnit is getting in the way of their test development)

The key point to keep in mind is that the Maven lifecycle uses the test phase for the execution of unit tests.

When it comes to integration tests there are two (and a half) schools of thought as to the right way to handle the tests with Maven.

This school of thought uses the phases after package to start up a container, run the integration tests, tear down the container, and finally check the test results and fail the build in the event of test failures.

mvn integration-test
mvn verify

So with this you do the following:

pre-integration-test
fork
=true
integration-test
post-integration-test
verify

For extra brownie points you would use build-helper-maven-plugin:reserve-network-port bound to the validate phase to ensure that the test server is started on an unused network port and then either use resource filtering against the test resources to pass the port through to the tests or use a system property passed through systemPropertyVariables to make the port number available to the tests.

  • If the tests fail, you cannot release the project
  • Can move the integration tests into a separate profile (by convention called run-its) if the tests are too slow to run every build.
  • Hard to run the tests from an IDE. All the integration tests start/end in IT and while Maven knows to run tests starting/ending in Test with Surefire and run tests starting/ending in IT with Failsafe, your IDE probably doesn't. Additionally, your IDE is not going to start the container for you, so you have to do a lot of work by hand to actually run the tests manually.

Debugging the tests potentially requires attaching two debuggers, e.g. one to debug the application running in container and the other to debug the test cases.

mvnDebug -Dmaven.failsafe.debug=true verify

This school of thought moves the integration tests into a separate module that depends on the war module and copies the war into the test resources using, e.g. dependency:copy-dependencies bound to the generate-test-resources phase coupled with a Tomcat7 dependency to test against.

The test cases themselves start up the Tomcat7 container using embedded mode

  • Tests can run in IDE
  • Integration tests are separated from Unit tests, so asking the IDE to run all tests will not kick off the slower tests
  • The war artifact is only rebuilt if you go past the package phase, consequently, you need to run at least mvn clean package periodically to refresh the code under test when using the IDE.
  • The failure of the integration tests does not break the build of the war module, so you can end up releasing a broken war artifact and then have the reactor build fail for the integration test module. Some people counteract this issue by having the integration test module within src/it and using Maven Invoker Plugin to run the tests... though that provides a poorer IDE integration, so I do not recommend that line.
  • Hard to get a consolidated test coverage report from Maven.

This is a kind of hybrid of the two approaches.

You use Failsafe to execute the tests, but the tests themselves are responsible for starting and stopping the Tomcat7 container that you want to test in.

  • Don't have to configure the server start/stop in Maven pom
  • IDE can safely run all tests (though the integration tests may be slower and you may want to not run them, but it's not like they will all fail unless there is a test failure)
  • Easier to debug the tests from your IDE (only one process to attach against, and the IDE usually makes it easy to debug tests by providing a special test runner)
  • Have to code the container start/stop yourself from within your test cases

I hope the above helps you understand the options you have. There may be other tweaks but in general the above are considered the best practice(s) for integration testing with Maven at present.

+1 One of the best answers on SO I have seen in a while.

I really like your response. There's just one thing that I'm fuzzy on: where did you figure out the convention of naming the profile that'll run integration tests "run-its"?

Lots of projects use that profile name, so it has become the convention... Especially as it is the convention we use in the maven project itself

Failsafe and integration-test/verify plus Eclipse: in our case, we generally run our app servers locally from Eclipse, and use the annotation @RunWith(SpringJUnit4ClassRunner.class) on our integration tests, which seems to be enough for Eclipse to recognise our unit tests.

Maven - deploy webapp to tomcat before JUnit test - Stack Overflow

maven tomcat junit maven-2 tomcat7
Rectangle 27 3

Answer before the test cases update

Use the following regex:

String rx = "-?0+\\.(0)+\\b|\\.0+\\b|\\b0+(?=\\.\\d*[1-9])|\\b0+(?=[1-9]\\d*\\.)|(\\.\\d*?)0+\\b";

The regex matches several alternatives and captures some parts of the string to later re-insert during replacement:

  • -?0+\.(0)+\b - matching an optional - followed with one or more 0s followed with a . and then captures exactly one 0 but matching one or more occurrences (because the (...) is placed on the 0 and the + is applied to this group); the word boundary at the end requires a non-word character to appear after the last matched 0. In the replacement, we restore the 0 with $1 backreference. So, -00.00 or 00.00 will be replaced with 0.
  • \.0+\b - a dot followed with one or more zeros before a , (since the string is comma-delimited).
  • \b0+(?=[1-9]\d*\.) - a word boundary followed by one or more zeros followed by a non-0 digit before a . (so, we remove all leading zeros from the integer part that is not equal to 0).
  • (\.\d*?)0+\b - capturing a .+zero or more digits, but as few as possible, up to the first 0, and then just matching one or more zeros (up to the end of string or ,) (so, we get rid of trailing zeros in the decimal part)

I suggest a very simple and short regex that does what you need:

Replace with $1.

String re = "-0+\\.(0)+\\b|\\.0+\\b|\\b0+(?=\\.\\d*[1-9])"; 
String str = "2.0,3.00,-4.0,0.00,-0.00,0.03,2.01,0.001,-0.03,101,0.001,-0.03";
String expected = "2,3,-4,0,0,.03,2.01,.001,-.03,101,.001,-.03"; 
System.out.println(str.replaceAll(re, "$1").equals(expected)); // TRUE
  • -0+\.(0)+\b - a minus followed with one or more 0s (0+) followed with a literal dot (\.) followed with one or more zeros (and capturing just the last 0 matched with (0)+) followed with a word boundary (location before , in this context)
  • \.0+\b - a literal dot (\.) followed with one or more zeros followed with a word boundary (location before , in this context)
  • \b0+(?=\.\d*[1-9]) - a word boundary (location after , in this context) followed with one or more zeros that must be followed with a literal dot (\.), then zero or more digits and then a digit from 1 to 9 range (so that the decimal part is more than 0).

@nKaushik: I wonder why you selected as accepted a solution that does not do what is asked for. Please check my answer.

@Wktor : I can change the accepted answer :) , also award is still open . Please check your pattern with ".50"

-0+\.(0)+\b|\.0+\b|\b0+(?=\.\d*[1-9])|\b0+(?=[1-9]\d*\.)|(\.\d*?)0+\b
$1$2

Have you had time to check? I see a lot more people have come up with their suggestion in the meantime :)

I also added the explanations for each alternation branch. If there is anything unclear, please drop a comment. Thank you for a nice riddle :)

Android/Java Regex to remove extra zeros from sub-strings - Stack Over...

java android regex string
Rectangle 27 3

Answer before the test cases update

Use the following regex:

String rx = "-?0+\\.(0)+\\b|\\.0+\\b|\\b0+(?=\\.\\d*[1-9])|\\b0+(?=[1-9]\\d*\\.)|(\\.\\d*?)0+\\b";

The regex matches several alternatives and captures some parts of the string to later re-insert during replacement:

  • -?0+\.(0)+\b - matching an optional - followed with one or more 0s followed with a . and then captures exactly one 0 but matching one or more occurrences (because the (...) is placed on the 0 and the + is applied to this group); the word boundary at the end requires a non-word character to appear after the last matched 0. In the replacement, we restore the 0 with $1 backreference. So, -00.00 or 00.00 will be replaced with 0.
  • \.0+\b - a dot followed with one or more zeros before a , (since the string is comma-delimited).
  • \b0+(?=[1-9]\d*\.) - a word boundary followed by one or more zeros followed by a non-0 digit before a . (so, we remove all leading zeros from the integer part that is not equal to 0).
  • (\.\d*?)0+\b - capturing a .+zero or more digits, but as few as possible, up to the first 0, and then just matching one or more zeros (up to the end of string or ,) (so, we get rid of trailing zeros in the decimal part)

I suggest a very simple and short regex that does what you need:

Replace with $1.

String re = "-0+\\.(0)+\\b|\\.0+\\b|\\b0+(?=\\.\\d*[1-9])"; 
String str = "2.0,3.00,-4.0,0.00,-0.00,0.03,2.01,0.001,-0.03,101,0.001,-0.03";
String expected = "2,3,-4,0,0,.03,2.01,.001,-.03,101,.001,-.03"; 
System.out.println(str.replaceAll(re, "$1").equals(expected)); // TRUE
  • -0+\.(0)+\b - a minus followed with one or more 0s (0+) followed with a literal dot (\.) followed with one or more zeros (and capturing just the last 0 matched with (0)+) followed with a word boundary (location before , in this context)
  • \.0+\b - a literal dot (\.) followed with one or more zeros followed with a word boundary (location before , in this context)
  • \b0+(?=\.\d*[1-9]) - a word boundary (location after , in this context) followed with one or more zeros that must be followed with a literal dot (\.), then zero or more digits and then a digit from 1 to 9 range (so that the decimal part is more than 0).

@nKaushik: I wonder why you selected as accepted a solution that does not do what is asked for. Please check my answer.

@Wktor : I can change the accepted answer :) , also award is still open . Please check your pattern with ".50"

-0+\.(0)+\b|\.0+\b|\b0+(?=\.\d*[1-9])|\b0+(?=[1-9]\d*\.)|(\.\d*?)0+\b
$1$2

Have you had time to check? I see a lot more people have come up with their suggestion in the meantime :)

I also added the explanations for each alternation branch. If there is anything unclear, please drop a comment. Thank you for a nice riddle :)

Android/Java Regex to remove extra zeros from sub-strings - Stack Over...

java android regex string
Rectangle 27 3

The problem is that your test runs too short. JIT has not enough time ...

Try repeating the test at least 200 times (instead of 15) and you'll see the difference.

Note that JIT compilation does not happen just once. Methods can be recompiled several times as JVM collects more runtime statistics. You've hit the situation where solveRecursive survived more levels of optimization than solveIterative.

In this answer I've described how JIT decides to compile a method. Basically there are two main compilation triggers: the method invocation threshold and the backedge threshold (i.e. loop iteration counter).

Note that those two methods have different compilation triggers:

solveRecursive
solveIterative

These thresholds are not equal, and it happens that on a short distance solveRecursive is compiled earlier. But as soon as solveIterative is optimized, it starts to perform even better.

There is also a trick to make solveIterative compiled earlier: move the innermost loop for (k = i; k < j; k++) to a separate method. Yes, it may sound strange, but JIT is better in compiling several small methods instead of compiling one big method. Smaller methods are easier to understand and to optimize not only for humans, but also for computers :)

To make sure the code has been compiled with -XX:+PrintCompilation the test should be run long enough so that you see all the methods have been compiled. +1

performance - Recursive version of Java function is slower than iterat...

java performance recursion jvm jit
Rectangle 27 85

Demo with Test Cases

// Requires a decimal and commas
^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?\.[0-9]{1,2}$

// Allows a decimal, requires commas
(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$

// Decimal and commas optional
(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$

// Decimals required, commas optional
^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?\.[0-9]{1,2}$

// *Requires/allows X here also implies "used correctly"
  • If decimals are optional and the number may start with a decimal, we need to make sure the input isn't blank: (?=.)
^\$?
-?
[1-9][0-9]{0,2}
  • Could almost be ([0-9]{1,3}), but that would allow "0,123"
  • One exception, can start with 0 in the case of "$0.50" or "0.50": |0
(,[0-9]{3})*
  • Remove ? before \. if you want to disallow numbers starting with "." or "$."
  • Requires or allows decimal (one or two digits): \.[0-9]{1,2} or (\.[0-9]{1,2})? respectively
  • End with $ (unescaped) to make sure there's nothing after a valid number (like $1,000.00b)

To use the regex, use the string's match method and encase the regex between two forward slashes.

// The return will either be your match or null if not found
yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);

// For just a true/false response
!!yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);
var tests = [
    "$1,530,602.24", "1,530,602.24", "$1,666.24$", ",1,666,88,", "1.6.66,6", ".1555."
];

var regex = /(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/;

for (i = 0; i < tests.length; i++) { 
  console.log(tests[i] + ' // ' + regex.test(tests[i]));
  document.write(tests[i] + ' // ' + regex.test(tests[i]) + '<br/>');
}

You should create a jsFiddle to prove it because this actually seems right

This is the best regex for this that I've seen to-date. Shame OP didn't mark as answer or comment why it's not accepted. You have my gratitude, regardless :)

I can't find the favorite flag for answers! Great response.

I tried removing the '$' proceeding '\.' in order to disallow the use of a dollar sign for "decimal and commas optional", but it still seems to be passing. Any thoughts? (?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)(\.[0-9]{1,2})?$

(?=.)^(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$

javascript - Regex currency validation - Stack Overflow

javascript regex currency
Rectangle 27 85

Demo with Test Cases

// Requires a decimal and commas
^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?\.[0-9]{1,2}$

// Allows a decimal, requires commas
(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$

// Decimal and commas optional
(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$

// Decimals required, commas optional
^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?\.[0-9]{1,2}$

// *Requires/allows X here also implies "used correctly"
  • If decimals are optional and the number may start with a decimal, we need to make sure the input isn't blank: (?=.)
^\$?
-?
[1-9][0-9]{0,2}
  • Could almost be ([0-9]{1,3}), but that would allow "0,123"
  • One exception, can start with 0 in the case of "$0.50" or "0.50": |0
(,[0-9]{3})*
  • Remove ? before \. if you want to disallow numbers starting with "." or "$."
  • Requires or allows decimal (one or two digits): \.[0-9]{1,2} or (\.[0-9]{1,2})? respectively
  • End with $ (unescaped) to make sure there's nothing after a valid number (like $1,000.00b)

To use the regex, use the string's match method and encase the regex between two forward slashes.

// The return will either be your match or null if not found
yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);

// For just a true/false response
!!yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);
var tests = [
    "$1,530,602.24", "1,530,602.24", "$1,666.24$", ",1,666,88,", "1.6.66,6", ".1555."
];

var regex = /(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/;

for (i = 0; i < tests.length; i++) { 
  console.log(tests[i] + ' // ' + regex.test(tests[i]));
  document.write(tests[i] + ' // ' + regex.test(tests[i]) + '<br/>');
}

You should create a jsFiddle to prove it because this actually seems right

This is the best regex for this that I've seen to-date. Shame OP didn't mark as answer or comment why it's not accepted. You have my gratitude, regardless :)

I can't find the favorite flag for answers! Great response.

I tried removing the '$' proceeding '\.' in order to disallow the use of a dollar sign for "decimal and commas optional", but it still seems to be passing. Any thoughts? (?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)(\.[0-9]{1,2})?$

(?=.)^(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$

javascript - Regex currency validation - Stack Overflow

javascript regex currency
Rectangle 27 12

How can we test it?

Answering late, but got a working solution which may help future visitors of this question.

I succeed on having a fat jar using only one Maven plugin and including:

compile
  • External dependencies required by the test code (in test scope)

Which basically means a fat jar with the addition of test classes (and their dependencies). The Maven Jar Plugin and its test-jar goal would not suit this need. The Maven Shade Plugin and its shadeTestJar option would not help neither.

So, how to create in Maven a fat jar with test classes and external dependencies?

The Maven Assembly Plugin is a perfect candidate in this case.

Here is a minimal POM sample:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample</groupId>
    <artifactId>sample-project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <descriptor>src/main/assembly/assembly.xml</descriptor>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>com.sample.TestMain</mainClass>
                                </manifest>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

The configuration above is also setting a main class defined in test classes (for a quick check whether it works or not, down on the answer). But that's not enough.

You also need to create a descriptor file, in the src\main\assembly folder an assembly.xml file with the following content:

<assembly
    xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>fat-tests</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <useProjectArtifact>true</useProjectArtifact>
            <unpack>true</unpack>
            <scope>test</scope>
        </dependencySet>
    </dependencySets>
    <fileSets>
        <fileSet>
            <directory>${project.build.directory}/test-classes</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>**/*.class</include>
            </includes>
            <useDefaultExcludes>true</useDefaultExcludes>
        </fileSet>
    </fileSets>
</assembly>

The configuration above is:

  • setting external dependencies to be taken from the test scope (which will also take the compile scope as well)
  • setting a fileset to include compiled test classes as part of the packaged fat jar
  • setting a final jar with fat-tests classifier (hence your final file will be something like sampleproject-1.0-SNAPSHOT-fat-tests.jar).

Build the jar:

mvn clean compile test-compile assembly:single

Running from the target folder:

java -jar sampleproject-1.0-SNAPSHOT-fat-tests.jar

We would get the main (from tests classes) executed. The main may invoke others tests or application code (and hence require external dependencies, in both compile or test scope) and everything would work fine.

From such a main, you could also invoke all of your test cases as following:

  • Add to the test suite the concerned tests
  • Invoke the test suite from your plain Java main
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ AppTest.class })
public class AllTests {

}

Note: in this case the test suite is only concerning the AppTest sample test.

Then you could have a main class as following:

import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;

public class MainAppTest {

    public static void main(String[] args) {
        System.out.println("Running tests!");

        JUnitCore engine = new JUnitCore();
        engine.addListener(new TextListener(System.out)); // required to print reports
        engine.run(AllTests.class);
    }
}

The main above would then execute the test suite which will in chain execute all of the configured tests.

Also, it's not necessary to include a main method. You can launch org.junit.runner.JUnitCore and specify any or all of your test methods and classes.

@AleksandrDubinsky and A_Di-Matteo : Thanks a lot for your answer. It helped and saved a lot of time :)

@A_Di-Matteo and AleksandrDubinsky - Thanks guys. It works great!

java - How to include test classes in Jar created by maven-shade-plugi...

java maven build dependencies maven-shade-plugin
Rectangle 27 800

If your object is myObject, and you want to test to see if it is an NSString, the code would be:

[myObject isKindOfClass:[NSString class]]

Likewise, if you wanted to test myObject for a UIImageView:

[myObject isKindOfClass:[UIImageView class]]

Note that there is also a isMemberOfClass: method that will check for class "exactness." Be careful with it though, as many Apple objects are actually Core Foundation types in disguise. (Eg. an NSString is more often an NSCFString, and isMemberOfClass: will return false for this comparison.)

Note this method is very slow!

Is that right knowing that NSString is a class cluster? (like NSNumber)

ios - In Objective-C, how do I test the object type? - Stack Overflow

ios objective-c
Rectangle 27 332

To test if object is an instance of class a:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.
[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a 
// given class.

To get object's class name you can use NSStringFromClass function:

NSString *className = NSStringFromClass([yourObject class]);

or c-function from objective-c runtime api:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);
if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

There is also a class method for this.

My understanding is that this only works for objects that inherit NSObject.

@afEkenholm - but not on iOS 4.x, just so we know.

class_getName
NSStringFromClass

How do I test which class an object is in Objective-C? - Stack Overflo...

objective-c
Rectangle 27 1058

You can check if [string length] == 0. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

There are some very rare NSStrings where this will result in a false negative (saying the string isn't empty, when, for practical purposes, it is). Consider @"\u200B" (consisting only of Unicode character ZERO WIDTH SPACE. Printing it out will print 0 characters (verify using monospaced font), but string.length will give 1. There are other Unicode characters (like OBJECT REPLACEMENT CHARACTER) which behave likewise. You may get the latter when parsing PDF text.

@fzwo not to be an arse, but in theory it doesn't give a false negative. It behaves exactly as you'd expect. Your interpretation of what ZERO WIDTH SPACE is doesn't really matter, because @"\u200B" is a character nonetheless so if you test for the string to be empty, it will say it isn't because there is a character in it. It's just not printable following the Unicode standard.

Of course it is technically correct, I'm not debating that. I just want to caution that this may not exhibit the intended or expected behavior, which is why I wrote "for practical purposes". It depends on the intended meaning of "empty".

It's not a false negative. A "zero worth space" is a unicode character like any other. It's just "worth remembering" if relevant to your app. (Great thinking, fzwo!)

Let me know if I'm wrong, but I think you could also omit == 0 part and add a negation in front: ![string length]. Seems more clean.

@lostintranslation nil and zero are the same value. This approach is still applicable in iOS7.

ios - How do I test if a string is empty in Objective C? - Stack Overf...

ios objective-c nsstring
Rectangle 27 1050

You can check if [string length] == 0. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

There are some very rare NSStrings where this will result in a false negative (saying the string isn't empty, when, for practical purposes, it is). Consider @"\u200B" (consisting only of Unicode character ZERO WIDTH SPACE. Printing it out will print 0 characters (verify using monospaced font), but string.length will give 1. There are other Unicode characters (like OBJECT REPLACEMENT CHARACTER) which behave likewise. You may get the latter when parsing PDF text.

@fzwo not to be an arse, but in theory it doesn't give a false negative. It behaves exactly as you'd expect. Your interpretation of what ZERO WIDTH SPACE is doesn't really matter, because @"\u200B" is a character nonetheless so if you test for the string to be empty, it will say it isn't because there is a character in it. It's just not printable following the Unicode standard.

Of course it is technically correct, I'm not debating that. I just want to caution that this may not exhibit the intended or expected behavior, which is why I wrote "for practical purposes". It depends on the intended meaning of "empty".

It's not a false negative. A "zero worth space" is a unicode character like any other. It's just "worth remembering" if relevant to your app. (Great thinking, fzwo!)

Let me know if I'm wrong, but I think you could also omit == 0 part and add a negation in front: ![string length]. Seems more clean.

ios - How do I test if a string is empty in Objective C? - Stack Overf...

ios objective-c nsstring
Rectangle 27 1049

You can check if [string length] == 0. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

There are some very rare NSStrings where this will result in a false negative (saying the string isn't empty, when, for practical purposes, it is). Consider @"\u200B" (consisting only of Unicode character ZERO WIDTH SPACE. Printing it out will print 0 characters (verify using monospaced font), but string.length will give 1. There are other Unicode characters (like OBJECT REPLACEMENT CHARACTER) which behave likewise. You may get the latter when parsing PDF text.

@fzwo not to be an arse, but in theory it doesn't give a false negative. It behaves exactly as you'd expect. Your interpretation of what ZERO WIDTH SPACE is doesn't really matter, because @"\u200B" is a character nonetheless so if you test for the string to be empty, it will say it isn't because there is a character in it. It's just not printable following the Unicode standard.

Of course it is technically correct, I'm not debating that. I just want to caution that this may not exhibit the intended or expected behavior, which is why I wrote "for practical purposes". It depends on the intended meaning of "empty".

It's not a false negative. A "zero worth space" is a unicode character like any other. It's just "worth remembering" if relevant to your app. (Great thinking, fzwo!)

Let me know if I'm wrong, but I think you could also omit == 0 part and add a negation in front: ![string length]. Seems more clean.

ios - How do I test if a string is empty in Objective C? - Stack Overf...

ios objective-c nsstring
Rectangle 27 15

This is one of the reasons why we move AutoMapper into a custom ActionResult or an ActionFilter. At some point, you only really want to test that you mapped Foo to FooDto, but not necessarily test the actual mapping. By moving AutoMapper into the layer boundaries (such as between controller an view), you can merely test what you're telling AutoMapper to do.

This is similar to testing a ViewResult. You don't test from a controller that a view was rendered, but rather that you told MVC to render such-and-such view. Our action result becomes:

public class AutoMapViewResult : ActionResult
{
    public Type SourceType { get; private set; }
    public Type DestinationType { get; private set; }
    public ViewResult View { get; private set; }

    public AutoMapViewResult(Type sourceType, Type destinationType, ViewResult view)
    {
        SourceType = sourceType;
        DestinationType = destinationType;
        View = view;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var model = Mapper.Map(View.ViewData.Model, SourceType, DestinationType);

        View.ViewData.Model = model;

        View.ExecuteResult(context);
    }
}

With a helper method on a base controller class:

protected AutoMapViewResult AutoMapView<TDestination>(ViewResult viewResult)
{
    return new AutoMapViewResult(viewResult.ViewData.Model.GetType(), typeof(TDestination), viewResult);
}

Which then makes the controller now only specify what to map to/from, instead of performing the actual mapping:

public ActionResult Index(int minSessions = 0)
{
    var list = from conf in _repository.Query()
                where conf.SessionCount >= minSessions
                select conf;

    return AutoMapView<EventListModel[]>(View(list));
}

At this point, I only need to test, "make sure that you're mapping this Foo object to this destination FooDto type", without needing to actually perform the mapping.

Here's an example of a test snippet:

var actionResult = controller.Index();

actionResult.ShouldBeInstanceOf<AutoMapViewResult>();

var autoMapViewResult = (AutoMapViewResult) actionResult;

autoMapViewResult.DestinationType.ShouldEqual(typeof(EventListModel[]));
autoMapViewResult.View.ViewData.Model.ShouldEqual(queryResult);
autoMapViewResult.View.ViewName.ShouldEqual(string.Empty);

How would this work with the new WebApi, where my Get method is returning an IEnumerable<MyType> and not an action result?

@sassyboy I tend to use an isolated service layer with web api, where you could create a similar abstraction of your own.

c# - After using Automapper to map a ViewModel how and what should I t...

c# asp.net-mvc tdd automapper mvccontrib-testhelper
Rectangle 27 45

As long as you only want to test...

Use the Graph API Explorer to generate a token with the permissions you want.

Then, just copy/paste the token at the end of each graph.facebook.com URL. For instance:

https://graph.facebook.com/v1.0/me/friends?access_token=<ACCESS_TOKEN>
https://graph.facebook.com/v1.0/me/friends?access_token=<what I get from the graph explorer>

wait a sec. it works :)_

How can I get access token from code?

Facebook Open Graph API Examples - How to get the access token? - Stac...

facebook facebook-graph-api
Rectangle 27 44

Maintaining the test code along with your production code

In the few years that I've been practicing Test Driven Development, I'd have to say the biggest downsides are:

TDD is best done in pairs. For one, it's tough to resist the urge to just write the implementation when you KNOW how to write an if/else statement. But a pair will keep you on task because you keep him on task. Sadly, many companies/managers don't think that this is a good use of resources. Why pay for two people to write one feature, when I have two features that need to be done at the same time?

Some people just don't have the patience for writing unit tests. Some are very proud of their work. Or, some just like seeing convoluted methods/functions bleed off the end of the screen. TDD isn't for everyone, but I really wish it were. It would make maintaining stuff so much easier for those poor souls who inherit code.

Ideally, your tests will only break when you make a bad code decision. That is, you thought the system worked one way, and it turns out it didn't. By breaking a test, or a (small) set of tests, this is actually good news. You know exactly how your new code will affect the system. However, if your tests are poorly written, tightly coupled or, worse yet, generated (cough VS Test), then maintaining your tests can become a choir quickly. And, after enough tests start to cause more work that the perceived value they are creating, then the tests will be the first thing to be deleted when schedules become compressed (eg. it gets to crunch time)

Ideally, again, if you adhere to the methodology, your code will be 100% tested by default. Typically, thought, I end up with code coverage upwards of 90%. This usually happens when I have some template style architecture, and the base is tested, and I try to cut corners and not test the template customizations. Also, I have found that when I encounter a new barrier I hadn't previously encountered, I have a learning curve in testing it. I will admit to writing some lines of code the old skool way, but I really like to have that 100%. (I guess I was an over achiever in school, er skool).

However, with that I'd say that the benefits of TDD far outweigh the negatives for the simple idea that if you can achieve a good set of tests that cover your application but aren't so fragile that one change breaks them all, you will be able to keep adding new features on day 300 of your project as you did on day 1. This doesn't happen with all those who try TDD thinking it's a magic bullet to all their bug-ridden code, and so they think it can't work, period.

Personally I have found that with TDD, I write simpler code, I spend less time debating if a particular code solution will work or not, and that I have no fear to change any line of code that doesn't meet the criteria set forth by the team.

TDD is a tough discipline to master, and I've been at it for a few years, and I still learn new testing techniques all the time. It is a huge time investment up front, but, over the long term, your sustainability will be much greater than if you had no automated unit tests. Now, if only my bosses could figure this out.

What was the rest of the sentence ending with "(cough VS Test), then main"?

+1 for the selling problem. :) I'm right now at a new company and thinking of how to create a culture which would allow skills to spread freely.

As you I consider that some consultant companies are taking advantage of pair programming and TDD just to get more money from their clients. It is pretty disappointing how these clients pay for ideas that seem reasonable at first glance such as two people think much better than 2 or that TDD assures that every line of code is tested, but in the end they are just excuses for making a client pay more for something just one person can do.

unit testing - Disadvantages of Test Driven Development? - Stack Overf...

unit-testing testing tdd
Rectangle 27 517

re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

If the value is not necessarily an integer, consider amending the regex appropriately; for instance:

^[0-9]+([.][0-9]+)?$
^-?[0-9]+([.][0-9]+)?$

+1 for this approach, but take care with decimals, doing this test with, by example, "1.0" or "1,0" prints "error: Not a number".

I find the ''exec > echo ...'' rather silly. Just ''echo ... >&2''

@Ben do you really want to handle more than one minus sign? I'd make it ^-? rather than ^-* unless you're actually doing the work to handle multiple inversions correctly.

@SandraSchlichting Makes all future output go to stderr. Not really a point to it here, where there's only one echo, but it's a habit I tend to get into for cases where error messages span multiple lines.

exec >&2

I'm not sure why the regular expression has to be saved in a variable, but if it's for the sake of compatibility I don't think it's necessary. You could just apply the expression directly: [[ $yournumber =~ ^[0-9]+$ ]].

linux - How do I test if a variable is a number in Bash? - Stack Overf...

linux bash shell
Rectangle 27 501

re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

If the value is not necessarily an integer, consider amending the regex appropriately; for instance:

^[0-9]+([.][0-9]+)?$
^-?[0-9]+([.][0-9]+)?$

+1 for this approach, but take care with decimals, doing this test with, by example, "1.0" or "1,0" prints "error: Not a number".

I find the ''exec > echo ...'' rather silly. Just ''echo ... >&2''

@Ben do you really want to handle more than one minus sign? I'd make it ^-? rather than ^-* unless you're actually doing the work to handle multiple inversions correctly.

@SandraSchlichting Makes all future output go to stderr. Not really a point to it here, where there's only one echo, but it's a habit I tend to get into for cases where error messages span multiple lines.

I'm not sure why the regular expression has to be saved in a variable, but if it's for the sake of compatibility I don't think it's necessary. You could just apply the expression directly: [[ $yournumber =~ ^[0-9]+$ ]].

linux - How do I test if a variable is a number in Bash? - Stack Overf...

linux bash shell
Rectangle 27 500

re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

If the value is not necessarily an integer, consider amending the regex appropriately; for instance:

^[0-9]+([.][0-9]+)?$
^-?[0-9]+([.][0-9]+)?$

+1 for this approach, but take care with decimals, doing this test with, by example, "1.0" or "1,0" prints "error: Not a number".

I find the ''exec > echo ...'' rather silly. Just ''echo ... >&2''

@Ben do you really want to handle more than one minus sign? I'd make it ^-? rather than ^-* unless you're actually doing the work to handle multiple inversions correctly.

@SandraSchlichting Makes all future output go to stderr. Not really a point to it here, where there's only one echo, but it's a habit I tend to get into for cases where error messages span multiple lines.

I'm not sure why the regular expression has to be saved in a variable, but if it's for the sake of compatibility I don't think it's necessary. You could just apply the expression directly: [[ $yournumber =~ ^[0-9]+$ ]].

linux - How do I test if a variable is a number in Bash? - Stack Overf...

linux bash shell