-1

I have an Application Class

  @SpringBootApplication
   public class Application{
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
     }
   }

I have a controller class

  @RestController
  public class HelloController {

   @RequestMapping("/")
   public String index() {
    return "Greetings from Spring Boot!";
   }

 }

And, I want to write a test case for Application Test, to make sure that instance is created of type HelloController

     @RunWith(SpringRunner.class)
     @SpringBootTest
     public class ApplicationTest{
        @Autowired
        private HelloController helloController;

       @Test
        public void test(){
          assertNotNull(helloController);
         }
       }

But, Im getting an error while auto wiring hellocontroller variable(No beans of helloController type found) . As per my understanding @SpringBootTest should create context and return an instance. We dont need to write any context xml or use any AnnotationConfig class to get the instance. What is missing?

2 Answers2

0

Sorry the earlier code I posted is wrong. so removed it

this seems more relevant Testing a controller with an auto wired component is null when calling the controller from a test case

profcalculus
  • 281
  • 3
  • 6
  • This also appears to be even better: https://stackoverflow.com/questions/39892534/testing-a-controller-with-an-auto-wired-component-is-null-when-calling-the-contr – profcalculus Oct 11 '19 at 13:51
  • I didnt resolve the issue, still im getting could not autowire. No bean of 'HelloController' type found. – user2514421 Oct 11 '19 at 14:00
  • sorry the earlier solution of creating a new instance is wrong. that is correct for service and not controller. could you try the above link – profcalculus Oct 11 '19 at 14:03
  • I looked into that solution, was able run application if i use Inject mocks instead of Autowired for HelloController. But Injectmock is you creating instance instead of retrieving from spring context. I want to test that scenario here. – user2514421 Oct 11 '19 at 14:10
  • the first answer on the above link: uses MockMvc which goes directly to the end point ("/url") which would go to your controller , you dont have to use injectmock. here you dont create an instance of controller but end up doing the same thing right ? – profcalculus Oct 11 '19 at 14:24
0

By adding class name in @SpringBootTest(Classes = {HelloController.class}) resolved issue.