1

I have a spring boot 2.2.4 project with a REST controller, a service and a JPA repository. I can use the karate mock servlet to define a mock for the controller and service, but I don't know what to do for the repository. The controller @Autowired the service. The service @Autowired the repository.

As a result I get this message when I run my karate test:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repository.EmployeeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

The MockServlet I am using is exactly this class from demo: MockSpringMvcServlet

With the MockConfig class similar to this: MockDemoConfig

Finally the karate-config.js file bootstraps the MockSpringMvServlet this way (as given in karate demo code):


function fn() {
  var config = {
    baseUrl: 'http://localhost:8080'
  };

  var Factory = Java.type('demo.MockSpringMvcServlet');
  karate.configure('httpClientInstance', Factory.getMock());

  return config;
}

Note: if i remove the JPA repository from the API call, then the Karate Mock Servlet works fine without the server running and the Karate test passes successfully.

Any idea how I would do this? If anyone can point me in the right direction I would appreciate it.

joe
  • 220
  • 2
  • 11

1 Answers1

0

Add methods to the MockDemoConfig that will return instances of the Service and Repository. You can see that Spring is trying to perform the auto-wire, but can't find the beans.

Because of all the "magic" that Spring Boot does, you will need to figure out exactly how to manually instantiate things like the DataSource which the Repository may be depending on. Unfortunately this is out of scope of my expertise. If you have some Spring knowledge you should be able to figure this out quickly - or there may be a helper / test annotation in the Spring Boot test libraries.

One hint is perhaps the answer lies in @SpringBootTest and friends - and you may be able to get the Service auto-wired into your JUnit test class. Then it may be a simple matter of using some Java singleton, which you can get a reference to in your karate-config.js and then take it from there.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Thanks Peter. I had understood that I needed a mock implementation. I was just looking for an example of what to do. – joe Mar 12 '20 at 19:04