GraphQL Причина: graphql.AssertException: необходимо предоставить сборщик данных. Как здесь заглушить сборщик данных?
Я пытаюсь написать тест JUnit для GraphQl с помощью Spring Boot. Мой тест не проходит при использовании нижеприведенного метода. Я получаю AsserException в treeWiring.abcFetcher. (Вызвано: graphql.AssertException: необходимо предоставить сборщик данных). Пожалуйста, помогите мне издеваться над сборщиком данных. Его значение отображается как null.
private RuntimeWiring buildWiring() {
return RuntimeWiring.newRuntimeWiring()
.type(newTypeWiring("Query")
.dataFetcher("xList", abcWiring.abcDataFetcher));
Ниже мой исходный класс
@Component
public class GraphQLProvider {
private GraphQL graphQL;
private TreeWiring abcWiring;
@Autowired
public GraphQLProvider(TreeWiring abcWiring) {
this.abcWiring = abcWiring;
}
@PostConstruct
public void init() throws IOException {
URL url = Resources.getResource("graphql/x.graphqls");
String sdl = Resources.toString(url, Charsets.UTF_8);
GraphQLSchema graphQLSchema = buildSchema(sdl);
Instrumentation instrumentation = new TracingInstrumentation();
DataLoaderRegistry registry = new DataLoaderRegistry();
DataLoaderDispatcherInstrumentation dispatcherInstrumentation
= new DataLoaderDispatcherInstrumentation(registry);
this.graphQL = GraphQL.newGraphQL(graphQLSchema).instrumentation(instrumentation).instrumentation(dispatcherInstrumentation).build();
}
private GraphQLSchema buildSchema(String sdl) {
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
RuntimeWiring runtimeWiring = buildWiring();
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
}
private RuntimeWiring buildWiring() {
return RuntimeWiring.newRuntimeWiring()
.type(newTypeWiring("Query")
.dataFetcher("xList", abcWiring.abcDataFetcher));
Ниже мой TestCLass:
@ContextConfiguration(classes = GraphQLProvider.class)
@SpringBootTest
@RunWith(SpringRunner.class)
public class GraphQLProviderTest {
@MockBean
TreeWiring treeWiring;
@MockBean
DataFetcher abcDataFetcher;
//@InjectMocks
//GraphQLProvider graphQLProvider = new GraphQLProvider(treeWiring);
@Autowired
@InjectMocks
GraphQLProvider graphQLProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetUserLabels() throws IOException {
Mockito.when(treeWiring.db2HealthDataFetcher).thenReturn(db2HealthDataFetcher);
graphQLProvider.init();
}
}
Ниже мой код TreeWiring:
@Component
public class TreeWiring {
@Autowired
public TreeWiring(OneRepository oneRepository,
TwoRepository twoRepository,
ThreeRepository threeRepository,
FourRepository fourRepository) {
this.oneRepository = oneRepository;
this.twoRepository = twoRepository;
this.threeRepository =threeRepository;
this.fourRepository = fourRepository;
}
DataFetcher abcDataFetcher = environment -> {
String eID = environment.getArgument("eId");
String dID = environment.getArgument("dId");
return oneRepository.getUserLabel(eID);
1 ответ
В вашем тестовом классе JUnit вы имитируете DataFetcher abcDataFetcher, но не настраиваете его для использования в классе TreeWiring. Вот почему вы получаете исключение NullPointerException при попытке его использовать.
Чтобы это исправить, вам необходимо правильно настроить макет abcDataFetcher и передать его экземпляру TreeWiring, используемому в вашем GraphQLProvider. Вот как вы можете это сделать:
- Измените тестовый класс, чтобы настроить макет abcDataFetcher и передать его экземпляру TreeWiring:
@ContextConfiguration(classes = GraphQLProvider.class)
@SpringBootTest
@RunWith(SpringRunner.class)
public class GraphQLProviderTest {
@MockBean
TreeWiring treeWiring;
@MockBean
DataFetcher abcDataFetcher;
@Autowired
GraphQLProvider graphQLProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
// Set up the mock behavior for abcDataFetcher
Mockito.when(treeWiring.abcDataFetcher).thenReturn(abcDataFetcher);
}
@Test
public void testGetUserLabels() throws IOException {
// You can optionally set up the behavior for abcDataFetcher here if needed.
// Mockito.when(abcDataFetcher.get(...)).thenReturn(...);
// Now, call the init() method on the graphQLProvider to test it.
graphQLProvider.init();
}
}
- Убедитесь, что класс TreeWiring правильно настроен с помощью abcDataFetcher:
@Component
public class TreeWiring {
private final OneRepository oneRepository;
private final TwoRepository twoRepository;
private final ThreeRepository threeRepository;
private final FourRepository fourRepository;
@Autowired
public TreeWiring(OneRepository oneRepository,
TwoRepository twoRepository,
ThreeRepository threeRepository,
FourRepository fourRepository,
DataFetcher abcDataFetcher) { // Inject the DataFetcher here
this.oneRepository = oneRepository;
this.twoRepository = twoRepository;
this.threeRepository = threeRepository;
this.fourRepository = fourRepository;
this.abcDataFetcher = abcDataFetcher; // Set the DataFetcher for this instance
}
// Rest of your TreeWiring class implementation...
}
Путем правильной настройки макета abcDataFetcher и передачи его классу TreeWiring проблема с нулевым значением должна быть решена, и ваш тест должен выполняться без каких-либо исключений NullPointerException.