在尝试模拟存储库以对Spring-Boot中的服务进行单元测试后,我发生了一些故障那就是我所拥有的(简体)
@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@SpringBootTest
@ActiveProfiles("test")
public class UserTest{
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserRepostiory userRepository;
@Before
public void setUp() {
User user = new User(1L, "email@email", "name");
when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
}
@Test
public void findUserByIdReturnsUser() {
User user = userService.getById(1L); => always throws error in Service, that no User is found with that Id, it calls the regular Repository: mock does nothing
assertEquals(1L,user.getId());
}
}
但是,当服务调用回购协议时,我永远都不会返回用户。我是单元测试的新手,我很确定,我在这里错过了一些东西。
when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));