Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc 从父类模拟方法_Spring Mvc_Mocking_Mockito_Junit4_Spring Test - Fatal编程技术网

Spring mvc 从父类模拟方法

Spring mvc 从父类模拟方法,spring-mvc,mocking,mockito,junit4,spring-test,Spring Mvc,Mocking,Mockito,Junit4,Spring Test,我有以下几节课: public class ControllerA { @Autowired private UserService userService; protected void methodControllerA() { userService.findAll(); .... } } public class ControllerB extends ControllerA { @Autowired

我有以下几节课:

public class ControllerA {

    @Autowired
    private UserService userService;

    protected void methodControllerA() {
       userService.findAll();
       .... 
    }   
}

public class ControllerB extends ControllerA {

    @Autowired
    private AccountService accountService;

    public void methodControllerB() {
        accountService.findAll();
        methodControllerA();    
    }       
}
我想测试ControllerB.methodControllerB()的行为,因此我创建了Junit类,如下所示:

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = {
    "classpath:services/testServiceContext.xml",
    "classpath:apply/applyController.xml",
    "classpath:testApplicationContext.xml",
    "classpath:testDatabaseMessageSource.xml",
    "classpath:controller/propertyeditors/propertyeditorsContext.xml"})
public class ControllerBTest {

    @Mock
    private AccountService accountService;

    @InjectMocks
    private ControllerB  controller;

    @Test
    public void methodControllerBTest() throws Exception {      

        controller = new ControllerB() {
            protected void methodControllerA() {                
            }
        };          
        controller.methodControllerB();
        asserts(); 
    }    

}
当然,当我实例化ControllerB()时,accountService不会被模拟,所以当调用accountService时,我会得到一个空指针,但是如果我不实例化ControllerB(),我就不能覆盖methodControllerA(),所以我会在这个方法内的Userservice中得到一个空指针。。。 有什么想法吗?谢谢

解决了

AccountServiceImp accountService = mock(AccountServiceImp.class);
controller = new ControllerB() {
            protected void methodControllerA() {                
            }
};          
controller.setAccountService(accountService);
controller.methodControllerB();

如何实例化accountService/UserService?有设置器或构造函数吗?我忘了代码中的@Autowired。EditedSpringApplicationContext将在测试中注入这两个类,您在哪里创建?通过@ContextConfiguration,我刚刚更新了代码