【问题标题】:Mocking methods from a parent Class来自父类的模拟方法
【发布时间】:2014-10-13 12:13:45
【问题描述】:

我有几个类如下:

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 中的空指针... 有任何想法吗 ?谢谢

【问题讨论】:

  • 如何实例化accountService/UserService?有setter或constructor吗?
  • 我忘记了代码中的@Autowired。已编辑
  • 您在哪里创建将在您的测试中注入这两个类的 spring ApplicationContext?
  • 通过@ContextConfiguration,我刚刚更新了代码

标签: spring-mvc mocking mockito junit4 spring-test


【解决方案1】:

解决了!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 2022-01-04
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多