GraphQLTestTemplate not getting autowired

4.3k Views Asked by At

I am using GraphQLTestTemplate to mock responses for queries.

@RunWith(SpringRunner.class)
@GraphQLTest
public class UnitTest {

    @Autowired
    private GraphQLTestTemplate graphQlTestTemplate ;
}

When i run unit test it is giving me error : org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.graphql.spring.boot.test.GraphQLTestTemplate' available: expected at least 1 bean which qualifies as autowire candidate.

pom.xml:

        <graphql-spring-boot-starter-test.version>5.0.2</graphql-spring-boot-starter-test.version>
        <graphql-java-tools.version>5.2.4</graphql-java-tools.version>
1

There are 1 best solutions below

0
On BEST ANSWER

Before giving you a working snippet we must clarify a few things.

  • I'm using : graphql-spring-boot-starter and
    graphql-spring-boot-starter-test , both of version 6.0.0.

    The latter is embedding junit 5 so you might not need to use need to use @RunWith

  • GraphQLTest is loading only a sliced context of your application, which are the beans related to GraphQL, this is to say, in your tests you should mock the beans that you are using under the hood, like a service your resolvers are using for example.

With that said: here is my working test example, Hope it helps.

@GraphQLTest
public class UserQueryIntTest {


    @Autowired
    private GraphQLTestTemplate graphQLTestTemplate;

    @MockBean
    UserService userServiceMock;


    @Test
    @WithMockUser(username = TEST_USERNAME)
    public void getUser() throws Exception {

        User user = new User();
        user.setUsername(TEST_USERNAME);
        user.setPassword(TEST_PASSWORD);
        doReturn(user).when(userServiceMock).getUser(TEST_USERNAME, TEST_PASSWORD);

        GraphQLResponse response = graphQLTestTemplate.postForResource("graphql/get-user.graphql");
        assertThat(response.isOk()).isTrue();
        assertThat(response.get("$.data.getUser.id")).isNotNull();
        assertThat(response.get("$.data.getUser.username")).isEqualTo(TEST_USERNAME);
    }
}