背景
我有一个简单的测试方法testFindByUserName。我使用mockito库。我有 @Mock UserMapper,它是由 Mapstruct 库创建的。
问题
Mocito 不处理我用来将用户映射到 userDto 的静态方法 INSTANCE。我有错误:错误:org.mockito.exceptions.misusing.MissingMethodInitationException: when() 需要一个参数,该参数必须是“模拟上的方法调用”。 例如: when(mock.getArticles()).thenReturn(articles);
此外,出现此错误的原因可能是: 1. stub 以下任一方法:final/private/equals()/hashCode() 方法。 这些方法无法被 stub /验证。 不支持在非公共(public)父类上声明的模拟方法。 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);
}
最佳答案
您需要使用PowerMockito要在 Mockito 测试中测试静态方法,请使用以下步骤:
@PrepareForTest(Static.class) // Static.class contains static methods
Call PowerMockito.mockStatic() to mock a static class (use PowerMockito.spy(class) to mock a specific method):
PowerMockito.mockStatic(Static.class);
Just use Mockito.when() to setup your expectation:
Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
关于java - 如何在测试过程中使用Mapstruct创建的映射器作为@Mock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49206709/