我有这样的 Controller
@Controller
public class MyController {
@Autowire
MyClass myClass;
//myClass doesn't have setter and getter
....
@RequestMapping("/path")
public String underTest(){
myClass.makeSomething();
return "html.jsp"
}
我想使用 Mockito 进行模拟测试并模拟 myClass。 在测试类中我想得到 myClass 这样:
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/BeanConfig.xml");
myClass = context.getBean("myClass ", MyClass .class);
但是我需要将此bean自动连接到 Controller 来测试 Controller 的方法(我认为测试代码不应该影响正常代码)。
有没有办法不用写set方法就可以实现?
我想检查 myClass.makeSomething() 是否在 underTest 方法中调用一次。
最佳答案
只要您对 MyController
的测试与 MyController
本身位于同一个包中(就像通常所做的那样 - 不同源文件夹中的相同包),您可以简单地分配它:
MyController controller = new MyController();
controller.myClass = mockMyClass;
这就是不要将 @Inject
/@Autowired
放在 private
字段上的原因。
关于java - 如果类没有 setter,如何将对象 Autowiring 到 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18635796/