My favorites | Sign in
Project Home Downloads Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Search
for
Unit_test  
Updated Jul 15, 2015 by luis.d.c...@gmail.com

No inheritance

<class>
Test - unit test
<feature>
Test - feature test
<method>
<expected input><expected behavior> - method test ex.) registerNewUserAccount_ExistingEmailAddressGiven_ShouldThrowException() no hardcoded values use constants instead test instantiation - factory for simple case, builder for many properties and lots of variation test assertion - use DSL (AssertJ) cleanup test - if this test fails, what business requirement is compromised? don't test implementation specific things

RegistrationForm registration = new RegistrationFormBuilder()

.email(REGISTRATION_EMAIL_ADDRESS) .firstName(REGISTRATION_FIRST_NAME) .lastName(REGISTRATION_LAST_NAME) .isSocialSignInViaSignInProvider(SOCIAL_SIGN_IN_PROVIDER) .build();

public class RegistrationFormBuilder {

private RegistrationForm registration;
public RegistrationFormBuilder() {
registration = new RegistrationForm();
}
public RegistrationFormBuilder email(String email) {
registration.setEmail(email); return this;
}
public RegistrationFormBuilder firstName(String firstName) {
registration.setFirstName(firstName); return this;
}
public RegistrationFormBuilder lastName(String lastName) {
registration.setLastName(lastName); return this;
}
public RegistrationFormBuilder isSocialSignInViaSignInProvider(SocialMediaService signInProvider) {
registration.setSignInProvider(signInProvider); return this;
}
public RegistrationForm build() {
return registration;
}
}

assertThatUser(createdUserAccount)
.hasEmail(REGISTRATION_EMAIL_ADDRESS) .hasFirstName(REGISTRATION_FIRST_NAME) .hasLastName(REGISTRATION_LAST_NAME) .isRegisteredUser() .isRegisteredByUsingSignInProvider(SOCIAL_SIGN_IN_PROVIDER);

public class UserAssert extends AbstractAssert<UserAssert, User> {

private UserAssert(User actual) {
super(actual, UserAssert.class);
}
public static UserAssert assertThatUser(User actual) {
return new UserAssert(actual);
}
public UserAssert hasEmail(String email) {
isNotNull();
Assertions.assertThat(actual.getEmail())
.overridingErrorMessage( "Expected email to be <%s> but was <%s>",
email, actual.getEmail()
) .isEqualTo(email);
return this;
}
public UserAssert hasFirstName(String firstName) {
isNotNull();
Assertions.assertThat(actual.getFirstName())
.overridingErrorMessage("Expected first name to be <%s> but was <%s>",
firstName, actual.getFirstName()
) .isEqualTo(firstName);
return this;
}
public UserAssert hasLastName(String lastName) {
isNotNull();
Assertions.assertThat(actual.getLastName())
.overridingErrorMessage( "Expected last name to be <%s> but was <%s>",
lastName, actual.getLastName()
) .isEqualTo(lastName);
return this;
}
public UserAssert isRegisteredByUsingSignInProvider(SocialMediaService signInProvider) {
isNotNull();
Assertions.assertThat(actual.getSignInProvider())
.overridingErrorMessage( "Expected signInProvider to be <%s> but was <%s>",
signInProvider, actual.getSignInProvider()
) .isEqualTo(signInProvider);
hasNoPassword();
return this;
}
private void hasNoPassword() {
isNotNull();
Assertions.assertThat(actual.getPassword())
.overridingErrorMessage("Expected password to be
<null>
but was <%s>",
actual.getPassword()
) .isNull();
}
public UserAssert isRegisteredUser() {
isNotNull();
Assertions.assertThat(actual.getRole())
.overridingErrorMessage( "Expected role to be
<role_user>
but was <%s>",
actual.getRole()
) .isEqualTo(Role.ROLE_USER);
return this;
}
}

NestedRunner for inner class Junit

public class BowlingGameTest { @Test public void perfectGame() throws Exception { roll(pins(10), times(12)); assertThat(game.score(), is(equalTo(300))); } private int pins(int n) { return n; } private int times(int n) { return n; } }

use inputstream instead of File use ByteArrayInputStream instead of FileInputStream new File("./src/test/data/catalog.xml"); String filePath = getClass().getResource("catalog.xml").getFile(); Always delete temporary file on @Before or use File.createTempFile("catalog", ".xml") which will generate a unique file name use CountDownLatch to wait for threads to finish executing before assertion can proceed avoid parameterized junit on too many input values always use fail in try catch in test methods or use @Test(expected = IOException.class) dont comment @Test if the method is failing just replace it with @Ignore when creating test method start with assertion and name it TODO() after you completed the test then rename the method assert should be specific not vague use Assume.assumeTrue for platform specific test change conditional statements with assert and split it to seperate methods one for true and one for false

import static org.hamcrest.MatcherAssert.; import static org.hamcrest.Matchers.; consult Hamcrest doc

is() allOf() anyOf() noneOf() not() instanceOf() notNullValue() nullValue() sameInstance() hasEntry hasKey hasValue hasItem hasItems hasItemInArray closeTo - for float greatherThan greatherThanOrEqualTo lessThan lessThanOrEqualTo equalToIgnoringCase equalToIgnoringWhiteSpace containString endsWith startsWith hasProperty

public class RegexMatcher extends TypeSafeMatcher

<string>
{

private final String regex;
private RegexMatcher(final String regex) {
this.regex = regex;
}
@Override public void describeTo(final Description description) {
description.appendText("matches regular expression=" + regex + "");
}
@Override public boolean matchesSafely(final String string) {
return string.matches(regex);
}

// matcher method you can call on this matcher class
public static RegexMatcher matchesRegex(final String regex) {
return new RegexMatcher(regex);
}

}

assertThat(s, RegexMatcher.matchesRegex("a*b*a"));

avoid complex private methods avoid final method and class avoid static method that you want to stub avoid instantitating objects inside a method that you want to stub pass it instead as parameter avoid logic on constructor moved that to protected method so that it can be overridden use inheritance only for polymorphism and not to reuse functionality wrap external libraries avoid accessing static singletons inside methods pass it to the object contruction instead

org.junit.rules

@Rule public MethodRule globalTimeout = new Timeout(20);

@Rule public ExpectedException thrown = ExpectedException.none();

@Test public void throwsExceptionWithCorrectMessage() { thrown.expect(RuntimeException.class); thrown.expectMessage("boom"); throw new NullPointerException("Ka-boom!"); }

@Rule public TemporaryFolder folder = new TemporaryFolder(); //takes care of cleaning up after each @Test

Powered by Google Project Hosting