EasyMock不使用模拟方法

问题描述 投票:0回答:1

我创建了以下测试。

@Test
public void whenCreate_ThenAccountsShouldBeFound() {
    Account account = new Account();
    account.setUsername("Test");
    account.setFirstName("FirstName");
    account.setLastName("LastName");
    account.setPassword("Password");
    account.setEmail("[email protected]");
    accountService.createAccount(account);

    Account a = new Account();
    a.setUsername("Teswt");
    a.setFirstName("FirstName");
    a.setLastName("LastName");
    a.setPassword("Password");
    a.setEmail("[email protected]");
    accountService.createAccount(a);
    AccountRepository accountRepository = createNiceMock(AccountRepository.class);
    expect(accountRepository.findAll()).andReturn(Collections.singletonList(a));
    replay(accountRepository);

    assertEquals("Username name should be Test", "Test", accountService.getAllAccounts().iterator().next().getUsername());
}

测试通过了,但我不知道为什么。通常,模拟方法应返回另一个对象,这将导致错误的测试结果。对我来说,模拟方法似乎不起作用,但是为什么呢?

spring easymock
1个回答
0
投票

实际上,模拟是正确的。只是您的代码是错误的。

您为AccountRepository创建了一个模拟,但没有将此模拟设置为accountService。因此,当您调用accountService.getAllAccounts()时,该accountService将调用真实的AccountRepository,而不是模拟的。因此,您将在DB中获得2个书面元素。

并且,将“测试”与返回列表的第一个元素进行比较时,断言是正确的。

要解决,只需将AccountRepository设置为accountService

AccountRepository accountRepository = createNiceMock(AccountRepository.class);
accountService.setAccountRespository(accountRepository);

就这些谢谢,Linh

© www.soinside.com 2019 - 2024. All rights reserved.