在Spring Boot服务层的单元测试中模拟原始String

时间:2020-02-19 18:01:03

标签: java spring junit mockito

我正在尝试为服务层方法编写单元测试,以按名称查找Player。该方法调用JPA存储库方法并返回Page对象。 我希望测试验证确实调用了存储库中的正确方法。

测试课程

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {PlayerService.class})
public class PlayerServiceTest {

    @Autowired
    PlayerService playerService;

    @MockBean
    PlayerRepository playerRepository;


    @Test
    public void whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(){
        Pageable pageableStub = Mockito.mock(Pageable.class);
        String name = "xxx";
        Mockito.when(playerRepository.findByNameContainingIgnoreCase(any(String.class), any(Pageable.class)))
                .thenReturn(any(Page.class));

        //1st attempt:
        //playerService.listPlayersByName(name, pageableStub);
        playerService.listPlayersByName(eq(name), pageableStub);

        verify(playerRepository).findByNameContainingIgnoreCase(any(String.class), any(Pageable.class));
    }

我的问题

测试失败,并显示一条消息:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.domin0x.player.PlayerServiceTest.whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(PlayerServiceTest.java:60)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

按照建议,我将name更改为eq(name),但这导致了另一个问题:

Argument(s) are different! Wanted:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
    <any java.lang.String>, <any org.springframework.data.domain.Pageable>);

Actual invocation has different arguments:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
null,     Mock for Pageable, hashCode: 309271464
;

任何建议我应该在考试中进行哪些更改?

服务类别

@Service
public class PlayerService {
    public Page<Player> listPlayersByName(String name, Pageable pageable) {
        return repository.findByNameContainingIgnoreCase(name, pageable);
    }

存储库界面

@Repository
public interface PlayerRepository extends JpaRepository<Player, Integer> {

    Page<Player> findByNameContainingIgnoreCase(String name, Pageable pageable);
}

1 个答案:

答案 0 :(得分:2)

我花了一些时间才弄清楚这一点。

thenReturn中,您正在呼叫any(Page.class)。相反,您应该返回实际的Page对象或模拟的Page对象)。

最好避免使用“ any”,除非您无法知道身份。

Page<Player> pageStub = (Page<Player>)Mockito.mock(Page.class);
Mockito.when(playerRepository.findByNameContainingIgnoreCase(name, pageableStub))
            .thenReturn(pageStub);

Page<PlayerStub> result = playerService.listPlayersByName(name, pageableStub);

assertSame(pageStub, result);

// No need to call verify, since it couldn't get pageStub without calling the correctly stubbed method.

为澄清起见:eq()any()和其他“匹配项”仅应用作whenverify中方法的参数。它们绝不能传递给测试对象,也不应从任何模拟对象中返回。