2016-07-10 68 views
1

我試圖單元測試一個服務方法。服務方法調用一個spring數據庫方法來獲取一些數據。我想嘲笑那個庫調用,並自己提供數據。怎麼做?在Spring Boot documentation之後,當我模擬存儲庫並在我的測試代碼中直接調用存儲庫方法時,模擬工作正常。但是當我調用服務方法時,這反過來會調用存儲庫方法,嘲笑不起作用。下面是示例代碼:如何模擬Spring數據和單元測試服務

服務類:

@Service 
public class PersonService { 

    private final PersonRepository personRepository; 

    @Autowired 
    public PersonService(personRepository personRepository) { 

     this.personRepository = personRepository; 
    } 

    public List<Person> findByName(String name) { 
     return personRepository.findByName(name); // I'd like to mock this call 
    } 
} 

測試類:

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class ApplicationTests { 

    // http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans 
    @MockBean 
    private PersonRepository personRepository; 

    @Autowired 
    private PersonService personService; 

    private List<Person> people = new ArrayList<>(); 

    @Test 
    public void contextLoads() throws Exception { 

     people.add(new Person()); 
     people.add(new Person()); 

     given(this.personRepository.findByName("Sanjay Patel")).willReturn(people); 

     assertTrue(personService.findByName("Sanjay Patel") == 2); // fails 
    } 
} 
+1

請出示一些代碼。你在服務中設置了嘲弄的存儲庫嗎?如果不是,那就很有必要。 – dunni

+0

哦!我需要手動注入服務中的存儲庫,對嗎?謝謝@dunni – Sanjay

+0

這取決於你的測試的樣子。正如我所說,發佈一些代碼。 – dunni

回答

1

大概倉庫標有@MockedBean註解。如果存儲庫是模擬的,我不知道Spring是否可以按類型自動連線。 你可以定義@Bean方法並返回Mockito.mock(X.class),這應該可以工作。

不確定你需要spring來測試服務方法。更簡單的方法是僅使用Mockito及其@InjectMocks註釋。

0

對於Spring數據存儲庫,您需要指定bean名稱。通過類型嘲笑似乎不起作用,因爲存儲庫是運行時的動態代理。

默認Bean名稱爲PersonRepository是 「personRepository」,所以這應該工作:

@MockBean("personRepository") 
private PersonRepository personRepository; 

下面是完整的測試:

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class ApplicationTests { 

    // http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans 
    @MockBean("personRepository") 
    private PersonRepository personRepository; 

    @Autowired 
    private PersonService personService; 

    private List<Person> people = new ArrayList<>(); 

    @Test 
    public void contextLoads() throws Exception { 

     people.add(new Person()); 
     people.add(new Person()); 

     given(this.personRepository.findByName("Sanjay Patel")).willReturn(people); 

     assertTrue(personService.findByName("Sanjay Patel") == 2); // fails 
    } 
}