简体   繁体   English

忽略Mockito中测试方法中的无效方法

[英]Ignoring not void method inside testing method in Mockito

In class Account I have a method public Account reserveA() which I want to test, inside reserveA is called a method public Bank DAO.createB() . 在类帐户中我有一个方法public Account reserveA()我想测试,在reserveA内部称为方法public Bank DAO.createB() Is there a way to call reserveA() in test method but ignore call DAO.createB() ? 有没有一种方法来调用reserveA()的测试方法,但忽略调用DAO.createB() Non of these methods are void. 这些方法中没有一个是无效的。 I tried: 我试过了:

doNothing().when(Account).reserveA(param1, param2);

but it's not the proper way. 但这不是正确的方法。

doNothing() is reserved only for void methods. doNothing()仅保留用于void方法。 If your method returns something, then you are required to do as well (or throw exception). 如果你的方法返回一些东西,那么你也需要做(或抛出异常)。 Depending on complexity of your Account.reserveString(), you may need to mock some more than just this one method call if result is used somewhere else. 根据Account.reserveString()的复杂性,如果在其他地方使用结果,则可能需要模拟一些方法调用。

Trying to use doNothing() on non-void method results in error: 尝试在非void方法上使用doNothing()会导致错误:

org.mockito.exceptions.base.MockitoException: 
Only void methods can doNothing()!
Example of correct use of doNothing():
    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called

Consider such classes: 考虑这样的类:

@Component
public class BankDao {
    public BankDao() {}

    public void createVoid() {
        System.out.println("sth - 1");
    }

    public String createString(){
        return "sth - 2";
    }
}

@Service
public class Account {
    @Autowired
    private final BankDao DAO;

    public Account(BankDao dao) {
        this.DAO = dao;
    }
    public void reserveVoid() {
        System.out.println("before");
        DAO.createVoid();
        System.out.println("after");
    }
    public void reserveString() {
        System.out.println(DAO.createString());
    }
}

For which Test class is made: 对于哪个Test类:

@RunWith(MockitoJUnitRunner.class)
public class AccountTest {
    @Mock
    private BankDao bankDao;

    @InjectMocks
    private Account account;

    @Test
    public void reserveVoid_mockBankDaoAndDontUseRealMethod() {
        doNothing().when(bankDao).createVoid();
        account.reserveVoid();
    }

    @Test
    public void reserveString_mockBankDaoAndDontUseRealMethod() {
        when(bankDao.createString()).thenReturn("nothing");
        account.reserveString();
    }
}

Running such a test will produce: 运行这样的测试将产生:

nothing
before
after

If you change @Mock to @Spy and remove lines with doNothing() and when(), then you'll be calling original methods. 如果将@Mock更改为@Spy并使用doNothing()和when()删除行,那么您将调用原始方法。 Result would be: 结果将是:

sth - 2
before
sth - 1
after

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM