【问题标题】:How to use the mapper created by Mapstruct as @Mock during testing如何在测试期间使用 Mapstruct 创建的映射器作为@Mock
【发布时间】:2018-08-18 18:57:04
【问题描述】:

上下文

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

问题

Mocito 不处理我用来将用户映射到 userDto 的静态方法 INSTANCE。我有错误:错误: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);
}

【问题讨论】:

  • 嗨,你找到解决这个问题的方法了吗?

标签: java unit-testing springmockito


【解决方案1】:

您需要使用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);

【讨论】:

    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2020-10-24
    • 2021-10-05
    • 2021-05-10
    • 2017-11-03
    • 1970-01-01
    • 2021-11-22
    • 2021-01-04
    相关资源
    最近更新 更多