Mockito Common methods and examples

Source: Internet
Author: User

Mockit is an open source mock frame, official website: http://mockito.org/, Source: Https://github.com/mockito/mockito

To use Mockit, you first need to introduce the corresponding jar package in our project, and for MAVEN projects, you need to add the following dependencies:

		<dependency>
			<groupId>org.mockito</groupId>
			<artifactid>mockito-core</ artifactid>
			<version>2.0.5-beta</version>
		</dependency>
In our actual use, we may also need to testng to organize the test case:

		<dependency>
			<groupId>org.testng</groupId>
			<artifactid>testng</artifactid >
			<version>6.8.8</version>
			<scope>test</scope>
		</dependency>

Before we proceed with the mock test example below, we will build two simple demo and parameterclass of the test class.

Demo.java:

Package com.anlegor.test;

public class Demo {

	private String name = "Laowang";
	private int age;

	Public Demo (String name, int age) {
		this.name = name;
		This.age = age;
	}

	public string speak (String str) {
		return str;
	}
	public string Talk (String str)
	{
		return str;
	}
	Public String methodnoparameters ()
	{
		return name;
	}

	Public String methodcustomparameters (parameterclass parameter,string str)
	{
		return str;
	}

	Public String methodhavechildobj (parameterclass parameter,string str)
	{
		parameter.childtalk (str);
		return str;

	}
}

Parameterclass.java

Package com.anlegor.test;

public class Parameterclass {public

	parameterclass () {

	} public

	String childtalk (String str)
	{
		return str;
	}

}

When we are doing mock-up, there are a few scenarios that are common:

1, the return of the structure of the non-parametric function

	/**
	 * Test parameterless function mock *
	/@Test (priority=0) public
	void Testreturndirect ()
	{
		String mocked = " Mocked Return ";
		Demo Demo  = Mockito.mock (demo.class);
		Mockito.when (Demo.methodnoparameters ()). Thenreturn (mocked);
		Assert.assertequals (Demo.methodnoparameters (), mocked);
	}

2, the structure has the basic type as the parameter return

	/**
	 * Test any basic type argument function mock
	 */
	@Test (priority=1) public
	void Testmethodwithparameter ()
	{
		String word= "mocked Return";
		Demo demo =  Mockito.mock (demo.class);
		Mockito.when (Demo.speak (mockito.anystring ())). Thenreturn (word);
		Assert.assertequals (Demo.speak ("Hello"), word);
	}

3, the structure has the basic type as the parameter, but only for the specific parameter input only the mock return value

	/**
	 * Test specific parameter mock */
	@Test (priority=2) public
	void Testmethodwithspecificparameter ()
	{
		String word= "mocked Return";
		Demo demo =  Mockito.mock (demo.class);
		Mockito.when (Demo.speak (Mockito.matches (". * Uncle $"))). Thenreturn (word);
		Assert.assertequals (Demo.speak ("Uncle Li Next Door"), word);
	

4, constructs the custom class as function parameter return, this kind of situation is slightly more complex, needs to implement a Matcher class

	/**
	 * Test custom type parameter mock
	 *
	/@Test (priority=3) public
	void Testmethodwithcustomparameter ()
	{
		String word= "mocked Return";
		Demo demo =  Mockito.mock (demo.class);
		Mockito.when (Demo.methodcustomparameters (Mockito.argthat (New Isparameterclass ()),
				mockito.anystring ()). Thenreturn (word);
		Assert.assertequals (Demo.methodcustomparameters (New Parameterclass (), "you guessed"), word);
	Customize a matching Matcher class
	Isparameterclass extends argumentmatcher<parameterclass> {public
	    Boolean matches (Object para) {
	        return para.getclass () = = Parameterclass.class;}
	 }

5. Construct NULL to return

	/**
	 * The function that tests the mock returns null
	 */
	@Test (priority=4) public
	void Testmethodwithreturnnull ()
	{
		String word= "mocked Return";
		Demo demo =  Mockito.mock (demo.class);
		Mockito.when (Demo.speak (mockito.anystring ())). Thenreturn (null);
		Assert.assertnotequals (Demo.speak ("you guessed"), word);
	}

6. The function that constructs the mock throws an exception, of course we can set expectedexceptions in testng to show that the declaration throws the exception of the specified type so that the case executes successfully

	/**
	 * The function that tests the mock throws an exception *
	/@Test (expectedexceptions= org.mockito.exceptions.base.mockitoexception.class,priority=5) public
	void Testmethodreturnexception ()
	{
		String word= "mocked Return";
		Demo demo =  Mockito.mock (demo.class);
		Mockito.when (Demo.speak (mockito.anystring ())). Thenthrow (New Exception ());
		Demo.speak ("you guessed");
	}

7, some repeated calls, we want to return a different mock value for each call

	/**
	 * Different calls to test mock return different values
	 *
	/@Test (priority=6) public
	void Testmethodmultidiffreturn ()
	{
		String word= "mocked Return 0";
		String word1= "mocked Return 1";
		Demo demo =  Mockito.mock (demo.class);
		Mockito.when (Demo.speak (mockito.anystring ())). Thenreturn (Word). Thenreturn (word1);
		Assert.assertequals (Demo.speak ("you guessed"), word);
		Assert.assertequals (Demo.speak ("you guessed"), word1);
	}

8. Verify that the function execution has been mock

	/**
	 * Verify that the method is being mock and call the/@Test for the parameter being executed
	(expectedexceptions= org.mockito.exceptions.misusing.notamockexception.class,priority=7) public
	void Testmockedmethodrun ()
	{
		String word= "mocked Return";
		Demo demo =  Mockito.mock (demo.class);
		Mockito.when (Demo.speak (mockito.anystring ())). Thenreturn (word);
		Assert.assertequals (Demo.speak ("you guessed"), word);
		Mockito.verify (Demo.speak ("you guessed"));
		The method call of the following parameter is not executed, so the exception of Notamockexception is thrown
		mockito.verify (Demo.speak ("Nicai"));
	}

If you are tired of the above repeated use of mockito.when***, you can simply import the org.mockito.mockito.* statically.

Of course, the role of Mockito is not only as above, more detailed use can refer to its very detailed help document:

Http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.