提问者:小点点

然后返回始终为空,Spring-Boot Junit5 Mockito


我正在尝试实现Mockito来测试特定方法,但. thenBack(…)似乎总是返回一个null对象,而不是我想要的:

我正在使用mockito 2.22.0和Junit-5和spring-boot 2.0.4。释放

用户结果用户=userService.save(userDto);上面一行返回总是空指针例外。不知道为什么结果用户总是重新调整空,

 @SpringBootTest
    public class UserServiceTests {
    
    @InjectMocks
    private UserService userService =new UserServiceImpl();
    
    @Mock
    private UserRepository userRepository;
    
    @Mock
    BCryptPasswordEncoder passwordEncoder;
    
    @BeforeEach
    void setUp() throws Exception{
        MockitoAnnotations.initMocks(this);
        
    }
    
    @DisplayName("Test saveRegistrationTest method making call to Repository")
    @Test
    public void saveRegistrationTest() {
        
        User user =new User();
        user.setFirstName("TestFN");
        user.setLastName("TestLN");
        user.setEmail("test@test.com");
        user.setPassword("7asdf7asdfi");
        
        User testUser =new User();
        testUser.setFirstName("TestFN");
        
        UserRegistrationDto userDto = new UserRegistrationDto();
        userDto.setFirstName("TestFN");
        
        when(userRepository.save(testUser )).thenReturn(user);
        
        **User resultUser=userService.save(userDto);**
        
        String firstName=(userService.save(userDto)).getFirstName();
        String lastName=(userService.save(userDto)).getLastName();
        String resultEmailFromRepo=(userService.save(userDto)).getEmail();
        String password=(userService.save(userDto)).getPassword();
        
        assertNotNull(user);
        assertEquals("TestLN", firstName);
        assertEquals("TestLN", lastName);
        assertEquals("test@test.com", resultEmailFromRepo);
        assertNotNull(password);
        assertEquals("7asdf7asdfi", password);
    }
 @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String firstName;
    private String lastName;
    private String email;
    private String password;
    
    @OneToMany(cascade = CascadeType.ALL)
    private List<Todo> todoList = new ArrayList<>();

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(
            name = "users_roles",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))
    private Collection<Role> roles;
public class UserRegistrationDto {

    @NotEmpty
    private String firstName;

    @NotEmpty
    private String lastName;

    @NotEmpty
    private String password;

    @NotEmpty
    private String confirmPassword;

    @Email
    @NotEmpty
    private String email;

    @Email
    @NotEmpty
    private String confirmEmail;

    @AssertTrue
    private Boolean terms;
   public User save(UserRegistrationDto registration){
        User user = new User();
        user.setFirstName(registration.getFirstName());
        user.setLastName(registration.getLastName());
        user.setEmail(registration.getEmail());
        user.setPassword(passwordEncoder.encode(registration.getPassword()));
        user.setRoles(Arrays.asList(new Role("TEST_USER")));
        user.setTodoList(null);
        return userRepository.save(user);
    }

共1个答案

匿名用户

@InjectMocks
private UserService userService = new UserServiceImpl();

这个“对象”从来不是Spring管理的!

@SpringBootTest
class UserServiceTest {
  @Autowired
  private UserService testee;

  @MockBean
  private UserRepository userRepoMock; // done!
  // ... many test methods, like: when(userRepoMock.xxx).thenYYY
  // testee.someMethod()
  // verify(userRepoMock...)
  // ...
}

服务看起来像:

@Service // or some other "spring managed bean"
public class UserService {
  @Autowired
  private UserRepository userRepository;
 ...
}

正如约翰内斯评论的那样:

@BeforeEach

在此设置中不需要(但不有害??!)。

当我们使用具体对象实例作为mockito的“参数匹配器”时:

when(userRepository.save(someObject)).thenReturn(someMock);

,我们应该确保,当(在测试期间):

userRepository(someOtherObject)

…被称为,

someObject.equals(someOtherObject)

…是true!(“平等匹配器”)

否则mockito不能'/不会匹配该调用。

我们可以通过实现(自定义)equals(和hashCode)方法来解决:

// e.g. with lombok:
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
// ...
class UserRegistrationDto {
  @EqualsAndHashCode.Include
  String name;
}

EqualsAndHashCode(推荐,但要做好!(龙目岛小字,或手册!))

或者通过使用“更广泛的参数匹配器”,例如:

when(userRepository.save(any(UserRegistrationDto.class)).thenReturn(myMockResponse);

…甚至:

when(userRepository.save(any(/*java.lang.Object*/))...

参数匹配器javadoc