4

PeopleListBeanなどのバッキングBeanがあります。目的は単純です。リポジトリから人のリストを返します。

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)で行われるため、リポジトリをいつ/どのようにモックするかです。したがって、クラスが構築された後、実際にメソッドをモックする前に「getPeople」メソッドが呼び出され、アサーションの不一致が発生します。

私は本当にいくつかの助け/ガイダンスに感謝します!

4

1 に答える 1

0

JUnitの@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() {

    }

    // .
    // .
    // .
}
于 2012-07-17T08:41:51.863 に答える