模拟存储库以在Spring中测试服务

问题描述 投票:0回答:2

在尝试模拟存储库以对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());

    }
}

但是,当服务调用回购协议时,我永远都不会返回用户。我是单元测试的新手,我很确定,我在这里错过了一些东西。

spring spring-boot unit-testing junit spring-test
2个回答
1
投票
when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.