Spring:已经调用了testscoped bean方法

时间:2016-06-14 17:47:23

标签: spring spring-mvc testing spring-boot requestscope

我目前正在使用Spring Boot 1.4。我正在创建我的测试,但在解决以下情况时需要一些帮助:

我有一个请求范围的bean,为了简单起见,让我们说它是一个带有属性,setter和getter的简单POJO。 我想创建一个测试,以确保该bean的setter被调用一次,并且只在请求中调用一次。

这是我的方法:

@Component
@RequestScope
public class MyRequestScopedBean {
    private String aProperty;

    public String getaProperty() {
        return aProperty;
    }

    public void setaProperty(String aProperty) {
        this.aProperty = aProperty;
    }
}


@Controller
public class SampleController {
    ...
    @GetMapping("/some-random-url")
    public String doSomething(MyRequestScopedBean myRequestScopedBean) {
        ...
        myRequestScopeBean.setaProperty("some random value");
        ...
    }
}

@RunWith(SpringRunner.class)
@WebMvcTest(SampleController.class)
@WebAppConfiguration()
public class SampleControllerTest {
    ...
    @MockBean
    private MyRequestScopedBean myRequestScopedBean;

    @Autowired
    private MockMvc mvc;
    ....
    @Test
    public void aPropertySetterShouldBeCalledOnceWhenInvokingURL() throws Exception {
        this.mvc.perform(get("/some-random-url")
            .accept(MediaType.TEXT_HTML));
        verify(myRequestScopedBean, times(1)).setaProperty(anyString());
    }
}

然而,测试失败表明从未调用过“setaProperty”。

我还检查了myRequestScopeBean.getaProperty值,但始终返回null。

我想问题是在“执行”结束后,控制器中注入的MyRequestScopeBean实例不再存在,因此,它与我的测试中注入的不同。

我有什么方法可以检查是否在请求中调用了这个setter方法?

提前致谢!

0 个答案:

没有答案
相关问题