Search code examples
javajmockit

How can I check a specific mocked instance is passed using JMockit?


I want to test the following code

BufferedReader reader = new BufferedReader(new FileReader(args[0]));

If I write a test like this, it works

@Mocked FileReader fileReader;
@Mocked BufferedReader bufferedReader;

//...

new NonStrictExpectations() {{
  new FileReader("filename"); times = 1;
  new BufferedReader(withAny(fileReader)); times = 1;
}};

However, this test does not make sure that the create FileReader is passed to the ctor of BufferedReader, only that a FileReader gets passed.

What I actually want is for the last line to be

new BufferedReader(withSameInstance(fileReader)); times = 1;

Unfortunately this doesn't work, as JMockit complains that the ctor of BufferedReader is never called with the specified argument...

I tried using @Captured on the fileReader but that didn't work either...


Solution

  • The ability that @Capturing mock fields had of getting new-ed instances assigned to them was removed in JMockit 1.6, in an attempt to simplify the API.

    With the current API (JMockit 1.6 & 1.7) you can still achieve the desired effect, in one of two ways:

    @Mocked FileReader fileReader;
    @Mocked BufferedReader bufferedReader;
    FileReader capturedReader;
    
    @Test
    public void mockIOClasses() throws Exception {
        new NonStrictExpectations() {{
            new FileReader("filename");
            result = new Delegate() {
                void captureIt(Invocation inv) {
                    capturedReader = inv.getInvokedInstance();
                }
            };
            times = 1;
    
            new BufferedReader(with(new Delegate<Reader>() {
                void check(Reader in) { assertSame(capturedReader, in); }
            }));
            times = 1;
        }};
    
        new BufferedReader(new FileReader("filename"));
    }
    
    @Test
    public void mockIOClasses2() throws Exception
    {
        new NonStrictExpectations() {{
            new FileReader("filename");
            result = new Delegate() {
                void captureIt(Invocation inv) {
                    capturedReader = inv.getInvokedInstance();
                }
            };
        }};
    
        new BufferedReader(new FileReader("filename"));
    
        new Verifications() {{
            FileReader r;
            new BufferedReader(r = withCapture());
            assertSame(capturedReader, r);
        }};
    }
    

    This said, however, I would recommend to avoid mocking the JRE IO classes. Both tests above are too tightly coupled to implementations details. The best approach is to just use a real file; you should be able to use a small test file (in the "test" source dir) here, perhaps creating it as a temporary file in the test itself.