我正确测试了吗?

时间:2017-02-15 16:14:57

标签: java spring unit-testing junit mockito

我在服务类上有以下方法:

@Service
public class Service {
    (...)
    public Page<ChannelAccount> getByCustomerAndChannelType(Pageable pageable, Customer customer, ChannelType channelType) {
        return channelAccountRepository.findByCustomerAndChannelType(pageable, customer, channelType);
    }
}

返回预期结果。现在我尝试为它构建单元测试。到目前为止我得到了这个:

@RunWith(MockitoJUnitRunner.class)
public class ChannelAccountServiceTest {
    @InjectMocks
    private ChannelAccountService channelAccountService;

    @Mock
    private ChannelAccountRepository channelAccountRepository;

    (...)
    @Test
    public void testGetByCustomerAndChannelTypePageable() {
        Page<ChannelAccount> pageResult = new PageImpl<>(channelAccountService.getAllChannelAccounts());
        Mockito.when(channelAccountRepository.findByCustomerAndChannelType(pageable, customer, ChannelType.FACEBOOK)).thenReturn(pageResult);
        Page<ChannelAccount> channelAccountPage = channelAccountRepository.findByCustomerAndChannelType(pageable, customer, ChannelType.FACEBOOK);
        assertEquals(pageResult, channelAccountPage);
    }

不知怎的,这感觉不对。我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

不确定为什么要调用此方法,因为它与案例本身无关:

Page<ChannelAccount> pageResult = new PageImpl<>(channelAccountService.getAllChannelAccounts());

我会在测试中执行以下操作:

Pageable pageableStub = Mockito.mock(Pageable.class);
Page pageStub = Mockito.mock(Page.class);

Mockito.when(channelAccountRepository
    .findByCustomerAndChannelType(pageableStub, customer, ChannelType.FACEBOOK))
    .thenReturn(pageStub);

Page<ChannelAccount> channelAccountPage = channelAccountService
    .findByCustomerAndChannelType(pageableStub, customer, ChannelType.FACEBOOK);

assertTrue(pageResult == channelAccountPage);

我会检查对象是否是相同的实例而不是equals(甚至更严格)。