我的服务测试失败,因为我在测试的类SpringBoot中有一个if语句

relj7zay  于 2022-09-19  发布在  Spring
关注(0)|答案(1)|浏览(170)

我正在从我的springboot应用程序编写测试。该类具有返回Optional<User>的方法getUserById。这种方法有一个if语句,它将在发送响应之前检查是否从存储库返回了行问题:*有了if语句,我的测试总是在if语句中抛出错误。当我删除if语句时,测试通过。我错过了什么?
这是我的
UserServiceImpl(测试中的类)**

@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
public class UserServiceImpl implements UserService, UserDetailsService {
    @Autowired
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    public List<User> getUsers() {
        log.info("Fetching users");
        return userRepository.findAll();
    }

    @Override
    public Optional<User> getUserById(Long id) {
        log.info("Fetching user id: {}", id);
        Optional<User> user = userRepository.findById(id);
        if (!user.isPresent()) {
            throw new ResourceNotFoundException(MessageUtil.ERROR_USER_NOTFOUND);
        }
        return user;
    }
}

这是我的UserServiceImplTest(测试类)

@RunWith(SpringRunner.class)
@SpringBootTest
class UserServiceImplTest {

    @MockBean
    private UserRepository userRepositoryTest;

    @InjectMocks
    private UserServiceImpl userServiceTest;

    @Mock
    private PasswordEncoder passwordEncoder;

    private List<User> userSet;
    private User user1;
    private User user2;

    @BeforeEach
    void setUp() {
        userServiceTest = new UserServiceImpl(userRepositoryTest, passwordEncoder);

        Set<ApplicationUserRole> roles = new HashSet<>();
        roles.add(ApplicationUserRole.TEST_USER);
        userSet = new ArrayList<>();

        user1 = User.builder().nickname("test-nickname")
                .id(1L)
                .username("254701234567")
                .roles(roles)
                .password("password")
                .build();

        user2 = User.builder().nickname("test2-nickname2")
                .id(2L)
                .username("254701234589")
                .roles(roles)
                .password("password")
                .build();

        userSet.add(user1);
        userSet.add(user2);

        userSet.stream().forEach(user -> {
            userServiceTest.saveUser(user);
        });
    }

    @AfterEach
    void tearDown() {
    }

    @Test
    void testGetUsers() {
        when(userServiceTest.getUsers()).thenReturn(userSet);
        assertEquals(2, userServiceTest.getUsers().size());
        verify(userRepositoryTest).findAll();
    }

    @Test
    void testGetUserById() {
        when(userServiceTest.getUserById(user1.getId())).thenReturn(Optional.ofNullable(user1));
        assertEquals(1, user1.getId());
        verify(userRepositoryTest).findById(user1.getId());
    }

    @Test
    void testSaveUser() {
        when(userServiceTest.saveUser(user1)).thenReturn(user1);
        assertEquals(1L, user1.getId());
        verify(userRepositoryTest).save(user1);
    }

    @Test
    void updateUser() {
        user1.setNickname("nickname-update");
        when(userServiceTest.saveUser(user1)).thenReturn(user1);
        assertEquals("nickname-update", user1.getNickname());
        verify(userRepositoryTest).save(user1);
    }

}

**注:*其他测试工作正常

g6baxovj

g6baxovj1#

您试图模拟服务方法调用,但服务是自动连接的-这不起作用。您可以模拟存储库方法调用,因为存储库被注解为MockBean,这应该可以工作。

相关问题