JSF Backing Bean单元测试

时间:2012-07-17 08:36:39

标签: java jsf junit mockito

我有一个名为eg的支持bean PeopleListBean。目的很简单:从存储库返回人员列表。

public class PeopleListBean {

    @Autowired
    private PersonRepository personRepository;

    private List<Person> people;

    @PostConstruct
    private void initializeBean() {     
        this.people = loadPeople();
    }

    public List<User> getPeople() {
        return this.people;
    }

    private List<Person> loadPeople() {
        return personRepository.getPeople();
    }

}

我想使用Junit和Mockito为这个bean创建一个单元测试 下面的示例测试类:

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.example.PersonRepository;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/test-application-context.xml" })
public class PeopleListBeanTest {

    @Autowired
    private PeopleListBean peopleListBean;
    @Autowired
    private PersonRepository mockPersonRepository;

    @Before
    public void init() {
        reset(mockPersonRepository);
    }

    @Test
    public void canListPeople() {
        List<Person> people = getDummyList();

        when(mockPersonRepository.getPeople().thenReturn(people);

        assertTrue(peopleListBean.getPeople().size() == people.size());
    }
}

我的问题是,何时/如何模拟存储库,因为加载发生在initializeBean方法(@PostConstruct)中。所以在课程建成之后,&#34; getPeople&#34;在我实际模拟方法之前调用方法会导致断言不匹配。

我真的很感激一些帮助/指导!

1 个答案:

答案 0 :(得分:0)

使用JUnit&#39; @BeforeClass注释

因此,您的代码如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/test-application-context.xml" })
public class PeopleListBeanTest {

    @Autowired
    private PeopleListBean peopleListBean;
    @Autowired
    private PersonRepository mockPersonRepository;

    @BeforeClass
    public static void initialise() {

    }

    // .
    // .
    // .
}