/java/

Mockito - Verifying

2013-10-16 22:52:33

import static org.junit.Assert.*;

import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.fest.assertions.Assertions.assertThat;

//@RunWith(MockitoJUnitRunner.class)
public class PostServiceTest {

    @Test
    public void save() {
        PostRepository rep = Mockito.mock(PostRepository.class);
        PostService postService = new PostService(rep);
        postService.save("lorem");
        //1
        Mockito.verify(rep, Mockito.times(1)).save(Mockito.anyString());
    }

    @Test
    public void testSave2() throws Exception {
        ArgumentCaptor

<string> arg = ArgumentCaptor.forClass(String.class);

        PostRepository rep = Mockito.mock(PostRepository.class);
        PostService postService = new PostService(rep);
        postService.save("lorem");
        //2
        Mockito.verify(rep, Mockito.times(1)).save(arg.capture());
        assertThat(arg.getValue()).isEqualTo("lorem");
    }

}
public class PostService {

    private PostRepository rep;

    public PostService(){

    }

    public PostService(PostRepository rep){
        this.rep = rep;
    }

    public void save(String name){
        rep.save(name);
    }
}

public class PostRepository {
    public void save(String name) {
    }
}