在尝试模拟存储库以对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());
}
}
但是,当服务调用回购协议时,我再也无法获得用户的返回。我是单元测试的新手,我可以肯定,我在这里错过了一些事情。
答案 0 :(得分:1)
在设置中,您执行以下操作:
when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
但是在测试中您打电话
User user = userService.getById(1L);
模拟getById或致电findById
答案 1 :(得分:0)
用@RunWith(SpringRunner.class)
注释测试类