我有春天接口UserDetailsService
的實現:我不能改寫的Mockito單元測試斯波克規格
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final UserEntity user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("Cannot find user with username " + username);
}
return new User(user);
}
}
UserRepository
是一個標準的接口extendng JpaRepository<UserEntity, Long>
其中UserEntity
是我的模型類。
User
是來自Spring Framework的UserDetails
的實現。
而且我使用JUnit和Mockito爲此方法編寫了單元測試。這些測試正在工作:
@RunWith(SpringRunner.class)
@DirtiesContext
public class UserDetailsServiceTest {
@Autowired
private UserDetailsService userDetailsService;
@Test
public void shouldFindUser() throws Exception {
// given
final UserEntity user = new UserEntity(
1L,
"username",
"[email protected]",
"password",
new ArrayList<>() // list of roles
);
when(UserDetailsServiceTestContext.userRepository.findByUsername(user.getUsername()))
.thenReturn(user);
// when
final UserDetails result = userDetailsService.loadUserByUsername(user.getUsername());
// then
assertThat(result).isEqualTo(UserFactory.create(user));
verify(UserDetailsServiceTestContext.userRepository)
.findByUsername(user.getUsername());
}
@Test(expected = UsernameNotFoundException.class)
public void shouldNotFindUser() throws Exception {
// given
when(UserDetailsServiceTestContext.userRepository.findByUsername(anyString()))
.thenReturn(null);
// when
final UserDetails result = userDetailsService.loadUserByUsername(new String());
}
@TestConfiguration
static class UserDetailsServiceTestContext {
@MockBean
private static UserRepository userRepository;
@Bean
UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl(userRepository);
}
}
}
現在我嘗試使用Groovy和Spock框架編寫這些測試。我寫了以下規範:
def 'should find user'() {
given:
def user = new UserEntity(
1L,
"username",
"[email protected]",
"password"
new ArrayList<>() // list of roles
)
userRepository.findByUsername(user.username) >> user
// userRepository.findByUsername(_ as String) >> user // also working
when:
def result = userDetailsService.loadUserByUsername(user.username)
then:
result == new User(user)
}
並且此測試正在工作。但是,當我想通過在then:
中添加一條語句1 * userRepository.findByUsername(user.username)
或1 * userRepository.findByUsername(_ as String)
來驗證userRepository的調用時,我收到一個錯誤UserDetailsServiceSpec.should find user and return new User:36 » UsernameNotFound
。管線36節when: