java - 我的测试正确吗?

标签 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);
    }

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

最佳答案

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

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(甚至更严格)。

关于java - 我的测试正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254600/

相关文章:

ruby - ruby rspec 的参数数量错误

unit-testing - 在一项 Angular Dart 测试中不能运行多个NgTestBed

java - 告诉 java 客户端代码接受自签名证书

java - JSR-303 验证组定义一个默认组

java printf 无法打印 char 数组

java - 使用 Spring boot 应用程序在 Angular 8 中配置 SSL 证书

java - 如何使用 JSON 在 Spring Rest 中接收和发送日期?

unit-testing - 使用 jest stub 函数

java - 如何在 Android 中从 Google 云端硬盘读取 .txt 文件?

Java SocketChannel 没有检测到断开连接?