@Autowired objects are null only when testing

前端 未结 1 375
南方客
南方客 2021-01-06 01:29

My question has to do with the application set-up, not mocking or using autowiring. See the answer for more details.

I\'m trying to set up a Spring Boot application

1条回答
  •  有刺的猬
    2021-01-06 01:56

    standaloneSetup is used for unit tests. But it seems like you are doing integrations tests, so the below code should work - I have not tested it.

    Replace

    @Before
    public void setup() throws Exception {
        mockMvc = standaloneSetup(new MetricAPI()).build();
    }
    

    with

    @Autowired
    private WebApplicationContext wac;
    
    @Before
    public void setup() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
    

    and add this to your test class:

    @WebAppConfiguration
    

    Bonus

    @RunWith(SpringRunner.class) tells JUnit to run using Spring’s testing support. SpringRunner is the new name for SpringJUnit4ClassRunner, it’s just a bit easier on the eye.

    0 讨论(0)
提交回复
热议问题