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

后端 未结 3 1355
陌清茗
陌清茗 2021-01-16 05:05

I have a controller

@RestController
public class Create {

    @Autowired
    private ComponentThatDoesSomething something;

    @RequestMapping(\"/greeting\         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-01-16 05:47

    Use Mockito and inject a mock that you create. I would prefer constructor injection:

    @RestController
    public class Create {
    
        private ComponentThatDoesSomething something;
    
        @Autowired
        public Create(ComponentThatDoesSomething c) {
            this.something = c;
        }
    }
    

    Don't use Spring in your Junit tests.

    public CreateTest {
    
        private Create create;
    
        @Before
        public void setUp() {
            ComponentThatDoesSomething c = Mockito.mock(ComponentThatDoesSomething .class);
            this.create = new Create(c);
        } 
    }
    

提交回复
热议问题