/java/

Junit reflection

2013-10-16 23:11:25

import static org.junit.Assert.*;

import java.lang.reflect.Field;

import org.junit.Test;
import org.mockito.Mockito;

import static org.fest.assertions.Assertions.assertThat;

public class ArticleServiceTest {

    @Test
    public void testName() throws Exception {
        String name = "lorem ipsum";

        ArticleService articleService = new ArticleService();
        articleService.save(name);

        Field field = ArticleService.class.getDeclaredField("desc");
        field.setAccessible(true);
        String fieldValue = (String) field.get(articleService);

        assertThat(fieldValue).isEqualTo(name);
    }
}
public class ArticleService {

    private String desc;

    public void save(String name){
        setNameToDesc(name);
    }

    private void setNameToDesc(String name) {
        this.desc = name;
    }

}