2013-06-13 17 views
12

Tôi muốn có thể Mockito thực hiện tác vụ tùy chỉnh khi phương thức void được gọi là.Thực hiện hành động tùy chỉnh khi phương thức void giả định được gọi là

Nói rằng tôi có đoạn mã sau:

@Autowired 
private ProfileService profileService; 

@Autowired 
private ProfileDao profileDao; 

private List<Profile> profiles; 

@Before 
public void setup() { 
    Mockito.when(profileDao.findAll()).thenReturn(profiles); 
    Mockito.when(profileDao.persist(any(Profile.class))).thenAddProfileToAboveList... 
} 

@Configuration 
public static class testConfiguration { 
    @Bean 
    public ProfileDao ProfileDao() { 
     return mock(ProfileDao.class); 
    } 
} 

Giả sử tôi muốn thêm một trường hợp hồ sơ vào danh sách hồ sơ. Mockito có thể làm điều đó không? Nếu thế thì sao?

Trả lời

19

Sử dụng Mockito.doAnswer.

doAnswer(new Answer() { 
    public Object answer(InvocationOnMock invocation) { 
     // make the changes you need here 
    }}) 
.when(mock).someMethod(); 
+0

Tôi có thể tìm hiểu thêm chi tiết về câu trả lời này không? OP đã yêu cầu thêm một Profile vào 'profiles', nhưng đoạn code trên không đề cập đến ... và danh sách' profiles' dường như nằm ngoài phạm vi của lớp bên trong - và tài liệu được liên kết dường như tập trung hơn vào thao tác mocks hơn là gọi mã không được mã hóa tùy ý. –

+0

https://stackoverflow.com/a/12088675/2112722 có nhiều chi tiết hơn ... –