简体   繁体   中英

Java Testing using Mock

Hello I am trying to make test cases using Mockito but I cant really figure it out how to use(Mockito) even to test simple methods. I have two methods how I can test them using mock objects?

public int addTwoNumbers(int a, int b)
{
return a+b;
}

public int divideTwoNumbers(int a, int b)
{
return a/b;
}

Unit test is supposed to test an individual unit of your source code. When having complex objects, that use various other components or libraries, it would be impossible to test just a selected piece of code without mocking behaviour of other components. Therefore, in your example there's absolutely no need for mocks, as there's no "external" behavior to be mocked.

Imagine you have a method that is supposed to send an e-mail. Obviously you use some component that handles the physical e-mail delivery and use it in your method. In such case you would mock the component that does the actual e-mail send and test whatever behaviour is implemented in your method (eg. message parsing, building subject, looking for delivery address).

Some most popular uses of Mockito include faking the actual method execution, where you simply define what to return, in case certain method is called and spying some object, where you verify whether certain method has been called and if so, how many times and/or what were the passed parameters (eg. a call to actual e-mail send with proper address, subject and message).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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