【问题标题】:Am I testing this correctly?我是否正确测试了这个?
【发布时间】:2017-02-15 16:14:56
【问题描述】:

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

@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);
    }

不知何故,这感觉不对。我在这里错过了什么?

【问题讨论】:

  • 您能否发布您如何定义 channelAccountService 和 channelAccountRepository。也只是 100% .. 这应该是单元测试而不是集成测试吧?
  • 不,该测试不测试除 Mockito 之外的任何东西。顾名思义,它应该测试服务,但它从不调用服务。它只调用模拟存储库,并测试存储库是否返回您告诉它返回的内容。
  • 是的,单元测试。问题已编辑显示如何将 channelAccountService 和 channelAccountRepository 插入到测试类中。

标签: java spring unit-testing junit mockito


【解决方案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);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多