How can I prevent RestAssured from overwriting mocks with real implementations?

I am trying to test the endpoint of a REST service using RestAssured while mocking my dependency. I use Spring to auto-detect the endpoint, and before I run the test, I install the mock dependency. However, when RestAssured calls the service, it restarts automatically again, and my layout is replaced with the actual implementation. How to prevent this?

I use Spring Boot, Jersey, EasyMock and RestAssured.

My endpoint class:

@Component
@Path("foo")
@Produces(MediaType.TEXT_PLAIN)
public class FooEndpoint {

    private FooService service;

    @GET
    @Produces({MediaType.TEXT_PLAIN})
    public String get() {
        return service.getFoo();
    }

    @Autowired
    public void setService(FooService service) {
        System.out.println(String.format("<<< Endpoint %s. Setting service %s", this, service));
        this.service = service;
    }

}

FooService:

@Service
public class FooService {

    public String getFoo() {
        return "real foo";
    }

}

Test:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class FooEndpointIT {

    @LocalServerPort
    private int port;

    @Autowired
    private FooEndpoint target;

    private FooService serviceMock;

    @Test
    public void testGet() {
        RestAssured.port = port;
        String expected = "mock foo";

        serviceMock = EasyMock.strictMock(FooService.class);
        target.setService(serviceMock);

        EasyMock.expect(serviceMock.getFoo()).andReturn(expected);
        EasyMock.replay(serviceMock);
        String actual = RestAssured.get("foo").body().asString();
        System.out.println(actual);
        assertEquals("mock foo", actual); // Fails: expected:<[mock] foo> but was:<[real] foo>
    }

}

And in the logs I see this:

<<< Endpoint com.foo.foo.FooEndpoint@6972c30a. Setting up the service com.foo.foo.FooService@57a48985

., Tomcat initializes and starts.,.

< < < com.foo.foo.FooEndpoint@6972c30a. EasyMock com.foo.foo.FooService
& ; < < com.foo.foo.FooEndpoint@6972c30a. com.foo.foo.FooService@57a48985
real foo

FooEndpoint , ?

+4

Source: https://habr.com/ru/post/1652465/


All Articles