Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

java - Mocking Objects Created Inside method Under test

I have a class which I would like to test.Whenever possible I would do dependency injections for that class which depends on object of other classes.But,I ran into a case where I would like to mock the object without restructuring the code and not appling DI.

Here is the class under test:

public class Dealer {

    public int show(CarListClass car){
        Print print=new Print();

        List<String> list=new LinkedList<String>();

        list=car.getList();
        System.out.println("Size of car list :"+list.size());

        int printedLines=car.printDelegate(print);
        System.out.println("Num of lines printed"+printedLines);

        return num;
    }
}

and my test class for this is:

public class Tester {
    Dealer dealer;

     CarListClass car=mock(CarListClass.class);  
     List<String> carTest;
     Print print=mock(Print.class);

    @Before
    public void setUp() throws Exception {
        dealer=new Dealer();
        carTest=new LinkedList<String>();
        carTest.add("FORD-Mustang");
        when(car.getList()).thenReturn(carTest);
        when(car.printDelegate(print)).thenReturn(9);
    }

    @Test
    public void test() {

        int no=dealer.show(car);
        assertEquals(2,number);//not worried about assert as of now

    }
}

I couldn't figure out a solution to mock the print object inside the Dealer class.Since,I mock it in the Test class,but it gets created in the method under test.I did my research,but couldn't find any good resource.

I know taking Print object creation out of this method and Injection the object is the better way,but I would like to test the code as it is ,with the print object being created inside the method.Is there any way to do this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you just want to mock the return value of car.printDelegate(), how about mock any Print instance for the call?

when(car.printDelegate(org.mockito.Matchers.any(Print.class))).thenReturn(9);

By the way, I'm confusing about your following code:-

List<String> list=new LinkedList<String>(); // allocate a empty list worth 
list=car.getList();                         // nothing but wasting memory.
...
return num; // no definition, do you mean printedLines?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...