我试图在我的控制器中用构造器注入来代替现场注入,因为这似乎是一种最佳实践。当我运行应用程序时,它同时适用于这两种解决方案。
我的问题是我的控制器的单元测试。我在使用字段注入的地方为Controller编写了测试类。效果很好。现在我用构造器注入代替了场注入。测试失败了。
下面是我的初始控制器(带有字段注入):
@Controller
public class DashboardController {
@Autowired
private MyService myService;
@RequestMapping("/")
public String index(Model model) {
MyPojo myPojo = myService.getMyPojo();
model.addAttribute("myPojo", myPojo);
return "dashboard";
}
}现在,新的控制器(通过注入构造器):
@Controller
public class DashboardController {
private final MyService myService;
@Autowired
public DashboardController(MyService myService) {
this.myService = myService;
}
@RequestMapping("/")
public String index(Model model) {
MyPojo myPojo = myService.getMyPojo();
model.addAttribute("myPojo", myPojo);
return "dashboard";
}
}而考试班:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyApplication.class})
@WebAppConfiguration
@TestPropertySource(locations = "classpath:/application.properties")
public class DashboardControllerUnitTests {
@InjectMocks
private DashboardController dashboardController;
@Mock
private MyService myService;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(dashboardController)
.build();
}
@Test
public void getDashboard() throws Exception {
doReturn(new MyPojo()).when(myService).getMyPojo();
mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(model().attribute("myPojo", equalTo(new MyPojo()))); // The test fail here
verify(myService).getMyPojo();
}
}如果我使用我的Controller的初始版本运行测试,它就能正常工作。但是,如果我使用新版本的Controller (使用构造函数注入)运行相同的测试,则myPojo为null,测试失败。
如果服务被注入构造函数,mockito就不会嘲笑它。你知道我为什么会有这个问题吗?如何解决?
发布于 2017-11-09 13:37:43
您需要将安装方法更改为如下所示:
@Before
public void setup() {
dashboardController = new DashboardController(myService);
mockMvc = MockMvcBuilders
.standaloneSetup(dashboardController)
.build();
}https://stackoverflow.com/questions/47203169
复制相似问题