{"id":4423,"date":"2021-07-03T10:44:17","date_gmt":"2021-07-03T10:44:17","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=4423"},"modified":"2021-07-04T16:10:09","modified_gmt":"2021-07-04T16:10:09","slug":"4423-2","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/4423-2\/","title":{"rendered":"Few Scenarios while Using Mockito"},"content":{"rendered":"<p><strong class=\"ctaHeader2\">How to Pass Interface or Abstract Class as Matcher?<\/strong><br \/>\n<strong>Person.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic interface Person {\r\n}\r\n<\/pre>\n<p><strong>StudentUtils.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n public String methodWithInterfaceArg(Person person)\r\n    {\r\n        \/\/This method takes Interface Implementation as Parameter\r\n        Somemethod(person);\r\n        return &quot;Test Success&quot;;\r\n    }\r\n\r\n    public void Somemethod(Person p){\r\n        System.out.println(&quot;Hello There&quot;);\r\n    }\r\n<\/pre>\n<p><strong>StudentUtilsTest.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n@Test\r\n    @DisplayName(&quot;Test for method which takes interface as argument&quot;)\r\n    void methodWithInterfaceArg() \r\n    {\r\n        Person objPerson = Mockito.mock(Person.class);\r\n\r\n        \/\/ Using spy we are creating a new mock and call the method to be tested\r\n        StudentUtils studentUtils= Mockito.spy(StudentUtils.class);\r\n\r\n        doNothing().when(studentUtils).Somemethod(objPerson);\r\n\r\n        \/\/ While testing we should call the method to be tested using new spyObject rather than systemUnderTest\r\n        \/\/ This is because only in the Spy object studentUtils we have created a mock definition for Somemethod\r\n        \/\/ Hence when methodWithInterfaceArg is called using systemUnderTest the mock  definition created using spy would be lost\r\n        assertEquals(&quot;Test Success&quot;, studentUtils.methodWithInterfaceArg(objPerson));\r\n    }\r\n<\/pre>\n<p><strong class=\"ctaHeader2\">How to doNothing when internal method which returns void is gets called?<\/strong><br \/>\n<strong>StudentUtils.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n    public String methodWithInterfaceArg(Person person)\r\n    {\r\n        \/\/This method has void return type\r\n        Somemethod(person);\r\n        return &quot;Test Success&quot;;\r\n    }\r\n\r\n    public void Somemethod(Person p){\r\n        System.out.println(&quot;Hello There&quot;);\r\n    }\r\n<\/pre>\n<p><strong>StudentUtilsTest.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n    @Test\r\n    @DisplayName(&quot;Test for internal method which is of void return type&quot;)\r\n    void methodWithInterfaceArg() {\r\n        Person objPerson = Mockito.mock(Person.class);\r\n\r\n        \/\/ Using spy we are creating a new mock and call the method to be tested\r\n        StudentUtils studentUtils= Mockito.spy(StudentUtils.class);\r\n\r\n        \/\/With Object Created using spy we can mock the actual method to do nothing\r\n        doNothing().when(studentUtils).Somemethod(objPerson);\r\n\r\n        assertEquals(&quot;Test Success&quot;, studentUtils.methodWithInterfaceArg(objPerson));\r\n    }\r\n<\/pre>\n<p><strong class=\"ctaHeader2\">How to doNothing when method which returns value is called?<\/strong><br \/>\n<strong>StudentUtils.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class StudentUtils {\r\n    private List arrStudents = new ArrayList();\r\n    private String Name = &quot;Mugil&quot;;\r\n\r\n    public String dummymethod(Student objStudent)\r\n    {\r\n        System.out.println(&quot;Dummy Method Called&quot;);\r\n        return &quot;Dummy Method&quot;;\r\n    }\r\n\r\n    public String methodCallingAnotherMethodReturningVal()\r\n    {\r\n        String something = dummymethod(new Student(&quot;102&quot; ,&quot;abc&quot;));\r\n        return &quot;Dummy Method returned &quot;+ something;\r\n    }\r\n}\r\n<\/pre>\n<p><strong>StudentUtilsTest.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n @Test\r\n    @DisplayName(&quot;Test for Method calling another method which returns value&quot;)\r\n    void methodCallingAnotherMethodReturningVal() {\r\n        StudentUtils studentUtils= Mockito.spy(StudentUtils.class);\r\n\r\n        Mockito.when(studentUtils.dummymethod(any())).thenReturn(&quot;Test Student&quot;);\r\n        Assert.assertEquals(&quot;Dummy Method returned Test Student&quot;, studentUtils.methodCallingAnotherMethodReturningVal());\r\n    }\r\n<\/pre>\n<p><strong class=\"ctaHeader2\">How to mock methods of private and public instance class variables?<\/strong><\/p>\n<ol>\n<li>The below scenario we are going to mock instance of method which belongs to other class initialized over by public and private class variables<\/li>\n<li>We Create a new mock and initialize using reflectionUtils for the objDBConnectionFactory which is private whereas we use a spy to directly change the method definition of objDBConnectionFactory2<\/li>\n<\/ol>\n<p><strong>DBConnectionFactory.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.org;\r\n\r\npublic class DBConnectionFactory {\r\n    public DBConnectionFactory() {\r\n    }\r\n\r\n    public &lt;T&gt; T  readDetails(byte&#x5B;] src, Class&lt;People&gt; valueType){\r\n        return (T)new Student();\r\n    }\r\n\r\n    public &lt;T&gt; T  readDetails2(String src){\r\n        return (T)new Student();\r\n    }\r\n}\r\n\r\n<\/pre>\n<p><strong>MockPrivateFileds.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.org;\r\n\r\nimport org.springframework.web.client.HttpStatusCodeException;\r\n\r\npublic class MockPrivateFileds {\r\n    private DBConnectionFactory objDBConnectionFactory = new DBConnectionFactory();\r\n\r\n    public DBConnectionFactory objDBConnectionFactory2 = new DBConnectionFactory();\r\n\r\n    private Student getDetails(HttpStatusCodeException httpStatusCodeException) {\r\n        return objDBConnectionFactory.readDetails(httpStatusCodeException.getResponseBodyAsByteArray(), People.class);\r\n    }\r\n\r\n    public Student getDetails2(HttpStatusCodeException httpStatusCodeException) {\r\n        return objDBConnectionFactory2.readDetails2(&quot;String&quot;);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>MockPrivateFiledsTest.java<\/strong><\/p>\n<pre class=\"brush: java; highlight: [39,40,44]; title: ; notranslate\" title=\"\">\r\npackage com.mugil.org;\r\n\r\nimport org.junit.jupiter.api.Test;\r\nimport org.junit.jupiter.api.extension.ExtendWith;\r\nimport org.mockito.InjectMocks;\r\nimport org.mockito.Mockito;\r\nimport org.mockito.junit.jupiter.MockitoExtension;\r\nimport org.springframework.test.util.ReflectionTestUtils;\r\nimport org.springframework.web.client.HttpStatusCodeException;\r\n\r\nimport static org.hamcrest.MatcherAssert.assertThat;\r\nimport static org.hamcrest.Matchers.instanceOf;\r\nimport static org.mockito.ArgumentMatchers.*;\r\n\r\n@ExtendWith({MockitoExtension.class})\r\nclass MockPrivateFiledsTest {\r\n    @InjectMocks\r\n    MockPrivateFileds systemUnderTest;\r\n\r\n    @Test\r\n    void getDetailsTest() {\r\n        HttpStatusCodeException httpStatusCodeException = Mockito.mock(HttpStatusCodeException.class);\r\n\r\n        \/*The Below two lines of code are needed because the objDBConnectionFactory created doesnot contain any definition of methods\r\n        * So the definition could be set by creating new mock object as below. If there is Setter we can use setter to set the newly created mock object\r\n        * Since there is no setter and its private we are going to use reflectionUtils *\/\r\n        DBConnectionFactory dbConnectionFactory = Mockito.mock(DBConnectionFactory.class);\r\n        ReflectionTestUtils.setField(systemUnderTest, &quot;objDBConnectionFactory&quot;, dbConnectionFactory);\r\n        Mockito.when(dbConnectionFactory.readDetails(nullable(byte&#x5B;].class), eq(People.class))).thenReturn(new Student());\r\n\r\n        assertThat(ReflectionTestUtils.invokeMethod(systemUnderTest, &quot;getDetails&quot;, httpStatusCodeException), instanceOf(Student.class));\r\n    }\r\n\r\n    @Test\r\n    void getDetailsTest2() {\r\n        HttpStatusCodeException httpStatusCodeException = Mockito.mock(HttpStatusCodeException.class);\r\n        systemUnderTest = Mockito.spy(MockPrivateFileds.class);\r\n\r\n        DBConnectionFactory dbConnectionFactory2 = Mockito.spy(DBConnectionFactory.class);\r\n        ReflectionTestUtils.setField(systemUnderTest, &quot;objDBConnectionFactory2&quot;, dbConnectionFactory2);\r\n\r\n        \/*Below is a mocking of a public method through its instance by using spy. The below case is similar to above\r\n        * scenario with the only difference we can use spy to gain access to readDetails2 *\/\r\n        Mockito.when(systemUnderTest.objDBConnectionFactory2.readDetails2(anyString())).thenReturn(new Student());\r\n\r\n        assertThat(systemUnderTest.getDetails2(httpStatusCodeException), instanceOf(Student.class));\r\n    }\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>How to Pass Interface or Abstract Class as Matcher? Person.java public interface Person { } StudentUtils.java public String methodWithInterfaceArg(Person person) { \/\/This method takes Interface Implementation as Parameter Somemethod(person); return &quot;Test Success&quot;; } public void Somemethod(Person p){ System.out.println(&quot;Hello There&quot;); } StudentUtilsTest.java @Test @DisplayName(&quot;Test for method which takes interface as argument&quot;) void methodWithInterfaceArg() { Person objPerson&hellip; <a href=\"https:\/\/codethataint.com\/blog\/4423-2\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[324],"tags":[335],"class_list":["post-4423","post","type-post","status-publish","format-standard","hentry","category-mockito","tag-mockito"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4423","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=4423"}],"version-history":[{"count":5,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4423\/revisions"}],"predecessor-version":[{"id":4428,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4423\/revisions\/4428"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=4423"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=4423"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=4423"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}