我有一个控制器
@RestController public class Create { @Autowired private ComponentThatDoesSomething something; @RequestMapping("/greeting") public String call() { something.updateCounter(); return "Hello World " + something.getCounter(); } }
我有该控制器的组件
@Component public class ComponentThatDoesSomething { private int counter = 0; public void updateCounter () { counter++; } public int getCounter() { return counter; } }
我还为我的控制器进行了测试。
@RunWith(SpringRunner.class) @SpringBootTest public class ForumsApplicationTests { @Test public void contextLoads() { Create subject = new Create(); subject.call(); subject.call(); assertEquals(subject.call(), "Hello World 2"); } }
控制器调用时测试失败something.updateCounter()。我得到一个NullPointerException。虽然我知道可以将其添加@Autowired到构造函数中,但我想知道是否可以对@Autowired字段进行此操作。如何确保@Autowired字段注释在测试中有效?
something.updateCounter()
NullPointerException
@Autowired
Spring不会自动线的组成部分,因为你实例化你的控制器, 新的 不使用Spring,因此组件不instatntiated
SpringMockMvc测试检查它是否正确:
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class CreateTest { @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context) .build(); } @Test public void testCall() throws Exception { //increment first time this.mvc.perform(get("/greeting")) .andExpect(status().isOk()); //increment secont time and get response to check String contentAsString = this.mvc.perform(get("/greeting")) .andExpect(status().isOk()).andReturn() .getResponse().getContentAsString(); assertEquals("Hello World 2", contentAsString); } }