Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returning a mocked object from a mocked service #1328

Open
kobbikobb opened this issue Mar 1, 2018 · 1 comment
Open

Returning a mocked object from a mocked service #1328

kobbikobb opened this issue Mar 1, 2018 · 1 comment

Comments

@kobbikobb
Copy link

kobbikobb commented Mar 1, 2018

thenAnswer does not work with a mocked object created inline in a method.

See below, do you think this should work?


   @Test
    public void doesNotWork() {
        ToyFactory toyFactory = mock(ToyFactory.class);
        when(toyFactory.create()).thenReturn(createToy()); // DOES NOT WORK
    }

    @Test
    public void works1() {
        ToyFactory toyFactory = mock(ToyFactory.class);
        when(toyFactory.create()).thenAnswer(x -> createToy()); // WORKS
    }

    @Test
    public void works2() {
        ToyFactory toyFactory = mock(ToyFactory.class);
        Toy toyVariable = createToy();
        when(toyFactory.create()).thenReturn(toyVariable); // WORKS
    }

    public Toy createToy() {
        Toy toy = mock(Toy.class);
        when(toy.getName()).thenReturn("Boy Toy");
        return toy;
    }

    public interface Toy {
        String getName();
    }

    public interface ToyFactory {
        Toy create();
    }

@TimvdLippe
Copy link
Contributor

This is probably related to our state-management with mocks and stubs. I wonder if #1264 addresses this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants