java - Use Mockito to mock some methods but not others -
is there way, using mockito, mock methods in class, not others?
for example, in (admittedly contrived) stock class want mock getprice() , getquantity() return values (as shown in test snippet below) want getvalue() perform multiplication coded in stock class
public class stock { private final double price; private final int quantity; stock(double price, int quantity) { this.price = price; this.quantity = quantity; } public double getprice() { return price; } public int getquantity() { return quantity; } public double getvalue() { return getprice() * getquantity(); } @test public void getvaluetest() { stock stock = mock(stock.class); when(stock.getprice()).thenreturn(100.00); when(stock.getquantity()).thenreturn(200); double value = stock.getvalue(); // unfortunately following assert fails, because mock stock getvalue() method not perform stock.getvalue() calculation code. assertequals("stock value not correct", 100.00*200, value, .00001); }
to directly answer question, yes, can mock methods without mocking others. called partial mock. see the mockito documentation on partial mocks more information.
for example, can following, in test:
stock stock = mock(stock.class); when(stock.getprice()).thenreturn(100.00); // mock implementation when(stock.getquantity()).thenreturn(200); // mock implementation when(stock.getvalue()).thencallrealmethod(); // real implementation
in case, each method implementation mocked, unless specify thencallrealmethod()
in when(..)
clause.
there possibility other way arround spy instead of mock:
stock stock = spy(stock.class); when(stock.getprice()).thenreturn(100.00); // mock implementation when(stock.getquantity()).thenreturn(200); // mock implementation // other method call use real implementations
in case, method implementation real one, except if have defined mocked behaviour when(..)
.
there 1 important pitfall when use when(object)
spy in previous example. real method called (because stock.getprice()
evaluated before when(..)
@ runtime). can problem if method contains logic should not called. can write previous example this:
stock stock = spy(stock.class); doreturn(100.00).when(stock).getprice(); // mock implementation doreturn(200).when(stock).getquantity(); // mock implementation // other method call use real implementations
however, example, believe still fail, since implementation of getvalue()
relies on quantity
, price
, rather getquantity()
, getprice()
, you've mocked.
what seems want just:
@test public void getvaluetest() { stock stock = new stock(100.00, 200); double value = stock.getvalue(); assertequals("stock value not correct", 100.00*200, value, .00001); }
Comments
Post a Comment