【发布时间】:2016-10-06 09:37:01
【问题描述】:
我有一个控制器
@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 字段注释在我的测试中有效?
【问题讨论】:
-
注入一个没有 Spring 的模拟。
-
你能用代码示例发布答案吗?
标签: java spring junit spring-boot autowired