2

上下文

我有一个简单的测试方法 testFindByUserName。我使用模拟库。我有由 Mapstruct 库创建的 @Mock UserMapper。

问题

Mocito 不处理我用来将用户映射到 userDto 的静态方法 INSTANCE。我有错误:error:org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个必须是“模拟方法调用”的参数。例如:when(mock.getArticles()).thenReturn(articles);

此外,此错误可能会出现,因为: 1. 您存根以下任一方法:final/private/equals()/hashCode() 方法。这些方法不能被存根/验证。不支持在非公共父类上声明的模拟方法。2. 在 when() 中,您不会在 mock 上调用方法,而是在其他对象上调用方法。

如何解决这个问题。

编码

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class UserServiceImplTest {

private User user;

private String token;

private UserDto userDto;


@InjectMocks
private UserServiceImpl userService;

@Mock
private UserMapper userMapper;

@Before
public void before() {
    user = new User(2L, "User_test",
            "firstName_test", "lastName_test",
            "test@test.pl", true, "password_test",
            "address_test", null,new ArrayList<>(),new ArrayList<>(), new HashSet<>());
    token = "test_token";
    userDto = new UserDto(2L, "User_test",
            "firstName_test", "lastName_test",
            "test@test.pl", true, "password_test",
            "address_test", null,new ArrayList<>(),new ArrayList<>(), new HashSet<>());

}

@Test
public void testFindByUsername() throws Exception {
    //Given
    String username= "User_test";

    when(userMapper.INSTANCE.userToUserDto(userRepository.findByUsername(username))).thenReturn(userDto);
    //When
    UserDto result = userService.findByUsername(username);

    //Then
    assertEquals("User_test", result.getUsername());
    assertEquals("firstName_test", result.getFirstName());
    assertEquals("lastName_test", result.getLastName());
    assertEquals("test@test.pl", result.getEmail());
    assertEquals("password_test", result.getPassword());
    assertEquals("address_test", result.getAddress());

}

我测试的方法

@Override
public UserDto findByUsername(final String username)  {
    User user = userRepository.findByUsername(username);
    if (user == null) {
        LOGGER.info("Not found user");
    }
        return mapper.INSTANCE.userToUserDto(user);
}
4

1 回答 1

0

您需要使用PowerMockito来测试 Mockito 测试中的静态方法,使用以下步骤:

@PrepareForTest(Static.class) // Static.class contains static methods

调用 PowerMockito.mockStatic() 模拟静态类(使用 PowerMockito.spy(class) 模拟特定方法):

PowerMockito.mockStatic(Static.class);

只需使用 Mockito.when() 来设置您的期望:

Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
于 2018-05-08T11:50:41.267 回答