Mocking new instance creation inside testing class using mockitoEfficiency of Java “Double Brace Initialization”?How to make mock to void methods with MockitoInjecting Mockito mocks into a Spring beanHow to mock an exception when creating an instance of a new class using MockitoMocking static methods with PowerMock and MockitoNeed to mock creation of a object inside a constructor of the class to be testedMockito: inject a class mock into a private interface fieldMocking constructor and static method from same class with Mockito and PowermockMock final class with Mockito 2Mockito cannot mock this class: interface

Which are the methodologies for interpreting Vedas?

Approach sick days in feedback meeting

Is it good practice to create tables dynamically?

Realistic, logical way for men with medieval-era weaponry to compete with much larger and physically stronger foes

Dedicated bike GPS computer over smartphone

Undocumented incompatibility between changes and siunitx?

Why would a car salesman tell me not to get my credit pulled again?

Am I being scammed by a sugar daddy?

Do Veracrypt encrypted volumes have any kind of brute force protection?

What's the difference between DHCP and NAT? Are they mutually exclusive?

Why didn't all the iron and heavier elements find their way to the center of the accretion disc in the early solar system?

Print "N NE E SE S SW W NW"

Is all-caps blackletter no longer taboo?

About the paper by Buekenhout, Delandtsheer, Doyen, Kleidman, Liebeck and Saxl

Why are ambiguous grammars bad?

Boss making me feel guilty for leaving the company at the end of my internship

Why would a home insurer offer a discount based on credit score?

Are athlete's college degrees discounted by employers and graduate school admissions?

Do they make "karaoke" versions of concertos for solo practice?

A team managed by my peer is close to melting down

Idiom for 'person who gets violent when drunk"

How to represent jealousy in a cute way?

ISP is not hashing the password I log in with online. Should I take any action?

Can I use 220 V outlets on a 15 ampere breaker and wire it up as 110 V?



Mocking new instance creation inside testing class using mockito


Efficiency of Java “Double Brace Initialization”?How to make mock to void methods with MockitoInjecting Mockito mocks into a Spring beanHow to mock an exception when creating an instance of a new class using MockitoMocking static methods with PowerMock and MockitoNeed to mock creation of a object inside a constructor of the class to be testedMockito: inject a class mock into a private interface fieldMocking constructor and static method from same class with Mockito and PowermockMock final class with Mockito 2Mockito cannot mock this class: interface






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am attempting to mock the new instance of an object inside the class I'm testing but I'm struggling to find a way to do this using Mockito.



If I understand this correctly, this might be something that can be achieved using Powermock but I only have Mockito at my disposal I can use.



Here's what I'm trying to do



 private class MyTestClass
private doSomethingMethod()
Object obj = new Object();
obj.getSomething;




I am currently spying on MyTest class and would like to mock the new Object so that I can manipulate the result of obj.getSomething()



Is this something achievable using Mockito?
Thank you










share|improve this question






















  • Unfortunately, Powermock(ito) is one answer. Mockito doesn't intercept object instantiation :( ** Edit - unless you move the object instantiation to a new package-visible method and then mock the response to that method in your spy. But then your code is written at the whim of your tests.

    – Not a JD
    Mar 25 at 0:47












  • Without PowerMock you will need to refactor your code to make the instance available for mocking, for example, moving your object creation to a factory or a provider method, and then mock the method/factory return accodingly

    – nullptr
    Mar 25 at 1:12












  • Check this out. But, as pointed out in the earlier comments, refactoring is required for sure. (though it is easy in PowerMock)

    – Aditya Bhardwaj
    Mar 25 at 7:26












  • Thank you guys, that's what I was afraid of, sadly refactoring is limited as this is legacy code and I'm trying to achieve some test coverage with minimal refactoring. Powermock seems like the only option. I'm just wondering, so far I'm using mockito, if I add powermock, will it start conflicting with my mockito tests?

    – Sgr
    Mar 25 at 8:55











  • @Sgr No it won't. We use Powermock along with Mockito and there are no conflicts.

    – Aditya Bhardwaj
    Mar 25 at 9:31

















0















I am attempting to mock the new instance of an object inside the class I'm testing but I'm struggling to find a way to do this using Mockito.



If I understand this correctly, this might be something that can be achieved using Powermock but I only have Mockito at my disposal I can use.



Here's what I'm trying to do



 private class MyTestClass
private doSomethingMethod()
Object obj = new Object();
obj.getSomething;




I am currently spying on MyTest class and would like to mock the new Object so that I can manipulate the result of obj.getSomething()



Is this something achievable using Mockito?
Thank you










share|improve this question






















  • Unfortunately, Powermock(ito) is one answer. Mockito doesn't intercept object instantiation :( ** Edit - unless you move the object instantiation to a new package-visible method and then mock the response to that method in your spy. But then your code is written at the whim of your tests.

    – Not a JD
    Mar 25 at 0:47












  • Without PowerMock you will need to refactor your code to make the instance available for mocking, for example, moving your object creation to a factory or a provider method, and then mock the method/factory return accodingly

    – nullptr
    Mar 25 at 1:12












  • Check this out. But, as pointed out in the earlier comments, refactoring is required for sure. (though it is easy in PowerMock)

    – Aditya Bhardwaj
    Mar 25 at 7:26












  • Thank you guys, that's what I was afraid of, sadly refactoring is limited as this is legacy code and I'm trying to achieve some test coverage with minimal refactoring. Powermock seems like the only option. I'm just wondering, so far I'm using mockito, if I add powermock, will it start conflicting with my mockito tests?

    – Sgr
    Mar 25 at 8:55











  • @Sgr No it won't. We use Powermock along with Mockito and there are no conflicts.

    – Aditya Bhardwaj
    Mar 25 at 9:31













0












0








0








I am attempting to mock the new instance of an object inside the class I'm testing but I'm struggling to find a way to do this using Mockito.



If I understand this correctly, this might be something that can be achieved using Powermock but I only have Mockito at my disposal I can use.



Here's what I'm trying to do



 private class MyTestClass
private doSomethingMethod()
Object obj = new Object();
obj.getSomething;




I am currently spying on MyTest class and would like to mock the new Object so that I can manipulate the result of obj.getSomething()



Is this something achievable using Mockito?
Thank you










share|improve this question














I am attempting to mock the new instance of an object inside the class I'm testing but I'm struggling to find a way to do this using Mockito.



If I understand this correctly, this might be something that can be achieved using Powermock but I only have Mockito at my disposal I can use.



Here's what I'm trying to do



 private class MyTestClass
private doSomethingMethod()
Object obj = new Object();
obj.getSomething;




I am currently spying on MyTest class and would like to mock the new Object so that I can manipulate the result of obj.getSomething()



Is this something achievable using Mockito?
Thank you







java initialization mockito spy






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 0:21









SgrSgr

268




268












  • Unfortunately, Powermock(ito) is one answer. Mockito doesn't intercept object instantiation :( ** Edit - unless you move the object instantiation to a new package-visible method and then mock the response to that method in your spy. But then your code is written at the whim of your tests.

    – Not a JD
    Mar 25 at 0:47












  • Without PowerMock you will need to refactor your code to make the instance available for mocking, for example, moving your object creation to a factory or a provider method, and then mock the method/factory return accodingly

    – nullptr
    Mar 25 at 1:12












  • Check this out. But, as pointed out in the earlier comments, refactoring is required for sure. (though it is easy in PowerMock)

    – Aditya Bhardwaj
    Mar 25 at 7:26












  • Thank you guys, that's what I was afraid of, sadly refactoring is limited as this is legacy code and I'm trying to achieve some test coverage with minimal refactoring. Powermock seems like the only option. I'm just wondering, so far I'm using mockito, if I add powermock, will it start conflicting with my mockito tests?

    – Sgr
    Mar 25 at 8:55











  • @Sgr No it won't. We use Powermock along with Mockito and there are no conflicts.

    – Aditya Bhardwaj
    Mar 25 at 9:31

















  • Unfortunately, Powermock(ito) is one answer. Mockito doesn't intercept object instantiation :( ** Edit - unless you move the object instantiation to a new package-visible method and then mock the response to that method in your spy. But then your code is written at the whim of your tests.

    – Not a JD
    Mar 25 at 0:47












  • Without PowerMock you will need to refactor your code to make the instance available for mocking, for example, moving your object creation to a factory or a provider method, and then mock the method/factory return accodingly

    – nullptr
    Mar 25 at 1:12












  • Check this out. But, as pointed out in the earlier comments, refactoring is required for sure. (though it is easy in PowerMock)

    – Aditya Bhardwaj
    Mar 25 at 7:26












  • Thank you guys, that's what I was afraid of, sadly refactoring is limited as this is legacy code and I'm trying to achieve some test coverage with minimal refactoring. Powermock seems like the only option. I'm just wondering, so far I'm using mockito, if I add powermock, will it start conflicting with my mockito tests?

    – Sgr
    Mar 25 at 8:55











  • @Sgr No it won't. We use Powermock along with Mockito and there are no conflicts.

    – Aditya Bhardwaj
    Mar 25 at 9:31
















Unfortunately, Powermock(ito) is one answer. Mockito doesn't intercept object instantiation :( ** Edit - unless you move the object instantiation to a new package-visible method and then mock the response to that method in your spy. But then your code is written at the whim of your tests.

– Not a JD
Mar 25 at 0:47






Unfortunately, Powermock(ito) is one answer. Mockito doesn't intercept object instantiation :( ** Edit - unless you move the object instantiation to a new package-visible method and then mock the response to that method in your spy. But then your code is written at the whim of your tests.

– Not a JD
Mar 25 at 0:47














Without PowerMock you will need to refactor your code to make the instance available for mocking, for example, moving your object creation to a factory or a provider method, and then mock the method/factory return accodingly

– nullptr
Mar 25 at 1:12






Without PowerMock you will need to refactor your code to make the instance available for mocking, for example, moving your object creation to a factory or a provider method, and then mock the method/factory return accodingly

– nullptr
Mar 25 at 1:12














Check this out. But, as pointed out in the earlier comments, refactoring is required for sure. (though it is easy in PowerMock)

– Aditya Bhardwaj
Mar 25 at 7:26






Check this out. But, as pointed out in the earlier comments, refactoring is required for sure. (though it is easy in PowerMock)

– Aditya Bhardwaj
Mar 25 at 7:26














Thank you guys, that's what I was afraid of, sadly refactoring is limited as this is legacy code and I'm trying to achieve some test coverage with minimal refactoring. Powermock seems like the only option. I'm just wondering, so far I'm using mockito, if I add powermock, will it start conflicting with my mockito tests?

– Sgr
Mar 25 at 8:55





Thank you guys, that's what I was afraid of, sadly refactoring is limited as this is legacy code and I'm trying to achieve some test coverage with minimal refactoring. Powermock seems like the only option. I'm just wondering, so far I'm using mockito, if I add powermock, will it start conflicting with my mockito tests?

– Sgr
Mar 25 at 8:55













@Sgr No it won't. We use Powermock along with Mockito and there are no conflicts.

– Aditya Bhardwaj
Mar 25 at 9:31





@Sgr No it won't. We use Powermock along with Mockito and there are no conflicts.

– Aditya Bhardwaj
Mar 25 at 9:31












1 Answer
1






active

oldest

votes


















0














IMHO everything is better in your case than using Powermock, as you already stated.



In similar cases I am using a solution which puts the "unmockable" code in an as-small-as-possible method and @Spy around like:



public class SpyTest 
@Spy
private MyTestClass myTestClass;

@Before
public void initMocks()
MockitoAnnotations.initMocks(this);


@Test
public void spyInsteadOfPowermock()
when(myTestClass.getObject()).thenReturn(Integer.valueOf(3));

assertThat(myTestClass.doSomethingMethod()).isEqualTo("3");


class MyTestClass
public String doSomethingMethod()
return getObject().toString();


Object getObject()
return new Object();








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55329877%2fmocking-new-instance-creation-inside-testing-class-using-mockito%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    IMHO everything is better in your case than using Powermock, as you already stated.



    In similar cases I am using a solution which puts the "unmockable" code in an as-small-as-possible method and @Spy around like:



    public class SpyTest 
    @Spy
    private MyTestClass myTestClass;

    @Before
    public void initMocks()
    MockitoAnnotations.initMocks(this);


    @Test
    public void spyInsteadOfPowermock()
    when(myTestClass.getObject()).thenReturn(Integer.valueOf(3));

    assertThat(myTestClass.doSomethingMethod()).isEqualTo("3");


    class MyTestClass
    public String doSomethingMethod()
    return getObject().toString();


    Object getObject()
    return new Object();








    share|improve this answer



























      0














      IMHO everything is better in your case than using Powermock, as you already stated.



      In similar cases I am using a solution which puts the "unmockable" code in an as-small-as-possible method and @Spy around like:



      public class SpyTest 
      @Spy
      private MyTestClass myTestClass;

      @Before
      public void initMocks()
      MockitoAnnotations.initMocks(this);


      @Test
      public void spyInsteadOfPowermock()
      when(myTestClass.getObject()).thenReturn(Integer.valueOf(3));

      assertThat(myTestClass.doSomethingMethod()).isEqualTo("3");


      class MyTestClass
      public String doSomethingMethod()
      return getObject().toString();


      Object getObject()
      return new Object();








      share|improve this answer

























        0












        0








        0







        IMHO everything is better in your case than using Powermock, as you already stated.



        In similar cases I am using a solution which puts the "unmockable" code in an as-small-as-possible method and @Spy around like:



        public class SpyTest 
        @Spy
        private MyTestClass myTestClass;

        @Before
        public void initMocks()
        MockitoAnnotations.initMocks(this);


        @Test
        public void spyInsteadOfPowermock()
        when(myTestClass.getObject()).thenReturn(Integer.valueOf(3));

        assertThat(myTestClass.doSomethingMethod()).isEqualTo("3");


        class MyTestClass
        public String doSomethingMethod()
        return getObject().toString();


        Object getObject()
        return new Object();








        share|improve this answer













        IMHO everything is better in your case than using Powermock, as you already stated.



        In similar cases I am using a solution which puts the "unmockable" code in an as-small-as-possible method and @Spy around like:



        public class SpyTest 
        @Spy
        private MyTestClass myTestClass;

        @Before
        public void initMocks()
        MockitoAnnotations.initMocks(this);


        @Test
        public void spyInsteadOfPowermock()
        when(myTestClass.getObject()).thenReturn(Integer.valueOf(3));

        assertThat(myTestClass.doSomethingMethod()).isEqualTo("3");


        class MyTestClass
        public String doSomethingMethod()
        return getObject().toString();


        Object getObject()
        return new Object();









        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 14:17









        mlemle

        1,4911320




        1,4911320





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55329877%2fmocking-new-instance-creation-inside-testing-class-using-mockito%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript