春天与Mockito:两个策略?

时间:2014-11-23 23:01:08

标签: java spring mockito

@InjectMocks的JavaDoc说:

  

如果使用构造函数成功创建了对象,那么   Mockito不会尝试其他策略。

但我有些疑惑。原因如下:

public class MyBean {
  private String path = "home";
  public void setPath(String path) { this.path = path; }
  public String path() { return path; }
}

@Controller
public class HomeController {

    private MyBean myBean;

    public HomeController(MyBean myBean) {

        System.out.println("HomeController(MyBean myBean)"); // always displays!!!

        // either:  <--- case 1
        MyBean bean = new MyBean();
        bean.setPath("home-modified");
        this.myBean = bean;

        // or:      <--- case 2
        this.myBean = null;
    }

    @RequestMapping("/")
    public String home() {
        System.out.println(myBean);
        return myBean.path();
    }
}

导致以下测试通过:

public class HomeControllerTest {

    @Spy private MyBean myBean;
    @InjectMocks private HomeController controller; 

    @Before
    public void initAnnotations() { MockitoAnnotations.initMocks(this); }

    @Test
    public void testAutowired() {
        assertThat(controller.home(), is("home"));
    }
}

但为什么myBean永远不会成为null(案例2)或代表我的自定义对象(案例1)?看起来Mockito违反了自己的JavaDoc?或者我会错过什么?

更新:与setter相同的事情

@Controller
public class HomeController {

    private  MyBean myBean;

    public HomeController(MyBean myBean) {
        this.myBean = myBean;
        System.out.println("HomeController(MyBean myBean)");
    }

    public void setMyBean(MyBean myBean) {
        System.out.println("setMyBean(MyBean myBean)");
        this.myBean = myBean;
    }

    @RequestMapping("/")
    public String home() {
        return myBean.path();
    }
}

显示器:

HomeController(MyBean myBean)
setMyBean(MyBean myBean)

这显然是“另一种策略”。

0 个答案:

没有答案