本文介绍了Mockito在使用@Mock时将Null值注入Spring bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于我是Spring Test MVC的新手,我不明白这个问题。我从 http://markchensblog.blogspot.in/search/label/Spring
变量 mockproductService
未从Application Context注入,它包含 null @Mock
注释并获得断言错误时code>值。
The Assertion error I currently encounter is as follows:
java.lang.AssertionError: Model attribute 'Products' expected:<[com.pointel.spring.test.Product@e1b42, com.pointel.spring.test.Product@e1f03]> but was:<[]>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.ModelResultMatchers$2.match(ModelResultMatchers.java:68)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at com.pointel.spring.test.ProductControllerTest.testMethod(ProductControllerTest.java:84)
注意:如果我使用 @Autowired
而不是 @Mock
它工作正常。
Note: If I use @Autowired
instead of @Mock
it is working fine.
RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:mvc-dispatcher-servlet.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class})
public class ProductControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@InjectMocks
private ProductController productController;
@Mock
//@Autowired
private ProductService mockproductService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
List<Product> products = new ArrayList<Product>();
Product product1 = new Product();
product1.setId(new Long(1));
Product product2 = new Product();
product2.setId(new Long(2));
products.add(product1);
products.add(product2);
Mockito.when(mockproductService.findAllProducts()).thenReturn(products);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testMethod() throws Exception {
List<Product> products = new ArrayList<Product>();
Product product1 = new Product();
product1.setId(new Long(1));
Product product2 = new Product();
product2.setId(new Long(2));
products.add(product1);
products.add(product2);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/products");
this.mockMvc.perform(requestBuilder).
andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.model().attribute("Products", products))
//.andExpect(MockMvcResultMatchers.model().size(2))
.andExpect(MockMvcResultMatchers.view().name("show_products"));
}
}
@Controller
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping("/products")
public String testController(ModelMap model){
model.addAttribute("Products",productService.findAllProducts());
return "show_products";
}
}
WebServletContext mvc-dispatcher-servlet.xml
WebServletContext mvc-dispatcher-servlet.xml
<bean id="someDependencyMock" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.pointel.spring.test.ProductService" />
</bean>
<context:component-scan base-package="com.pointel.spring.test" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
推荐答案
对我来说,目前还不清楚Spring和Mockito的组合当你从引用的博客源中获取它应该按预期工作。至少我可以解释你的观察结果:
- Your test (
this.mockMvc.perform()
) is working on the web application context created by Spring. In that contextProductController
was instantiated by Spring (context:component-scan
). TheproductService
was then autowired with the Mockito mock you created inmvc-dispatcher-servlet.xml
assomeDependencyMock
. - If you inject the
mockproductService
via@Autowired
, Spring injects thesomeDependencyMock
instance from its context. So yourMockito.when()
call works correctly on this instance, which was already correctly wired to theProductController
as mentioned before. - But if you inject the
mockproductService
via@Mock
, Mockito injects a new instance ofProductService
, not the one of the Spring context, since it knows nothing about Spring at all. So yourMockito.when()
call does not operate on the mock which was autowired by Spring and thussomeDependencyMock
stays uninitialized.
So what's left unclear for me about how the original code from the blog worked at all is:
这篇关于Mockito在使用@Mock时将Null值注入Spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!