/java/

Object Builder for Object.

2013-08-21 20:02:38

PostBuilder

package pl.btbw.builder.object;

import pl.btbw.entiti.Post;

public class PostBuilder {

    private int id;
    private String name;
    private String description;

    public static PostBuilder aPost(){
        return new PostBuilder();
    }

    public PostBuilder withId(int id){
        this.id = id;
        return this;
    }

    public PostBuilder withName(String name){
        this.name = name;
        return this;
    }

    public PostBuilder withDescription(String description){
        this.description = description;
        return this;
    }

    public Post build(){
        Post post = new Post();
        post.setId(id);
        post.setName(name);
        post.setDescription(description);
        return post;
    }   
}

PostServiceTest.java

package pl.btbw.service;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.startsWith;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import pl.btbw.builder.object.PostBuilder;
import pl.btbw.entiti.Post;

public class PostServiceTest {

    PostService postService = new PostService();

    Post post = null;
    Post post2 = null;

    @Before public void
    before(){
        this.post = PostBuilder.aPost()
                .withId(1).withName("lorem")
                .withDescription("desc")
                .build();

        this.post2 = PostBuilder
                .aPost()
                .withId(2)
                .withName("lorem")
                .withDescription("desc")
                .build();
    }

    @Test public void 
    shouldNotBeTheSame() {
        assertThat(post).isNotEqualTo(post2);
    }

    @Test public void
    shouldListContentPost(){
        List

<post> posts = new ArrayList<post>();
        posts.add(post);
        posts.add(post2);
        posts.add(null);

        assertThat(posts).contains(post).hasSize(3);

    }
}

More about "JUnit with Mockito and FEST Fluent Assertions" you can read on Codeleak http://blog.codeleak.pl/2013/07/test-code-readability-improved-junit.html

Post.java

package pl.btbw.entiti;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class Post {
    private int id;
    private String name;
    private String description;

    public Post() {
    }

    // set and get

    @Override
    public int hashCode() {
        ...
    }

    @Override
    public boolean equals(Object obj) {
        ...
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }   
}