I have a test class in Junit4 that needs to use NutrientListService.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
private NutrientListService nutrientService;
@Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}
I was getting a null nutrientService, so I tried to set up an ApplicationContext.
@Configuration
@ComponentScan("myservice")
@ComponentScan("myrepository")
public class ApplicationContext {
@Autowired
NutrientListService nutrientService;
}
However, I get
Error creating bean with name 'nutrientListService': Unsatisfied dependency expressed through field 'nutrientListRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repositories.NutrientListRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
This is the service:
@Service
@Component
public class NutrientListService {
@Autowired
private NutrientListRepository repo;
}
And the repository:
@Repository
public interface NutrientListRepository extends MongoRepository<MyClass, String> {
MyClass findByID(String ID);
}
Any ideas to wire the service properly? I need to pass it for calculation as it is one of the parameters. Do I have to use an application context class or the application-context.xml (which I could not find)? What would be the least obscure way to do this? I thank you.
@Configuration
@ComponentScan("myservice")
@ComponentScan("myrepository")
public class ApplicationContext {
@Bean
NutrientListService nutrientService(){
new NutrientListService()
}
}
And then call the Bean with @Autowired
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
@Autowired
NutrientListService nutrientService
@Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}