JMockit @mocked 注释标签

使用场景举例,我们做代码测试时会遇到待测代码调用其他人写的函数的情况,常规办法是修改源代码进行模拟返回,临时跳过别人的代码,这种方法容易产生隐藏的风险,例如没有及时改回去,导致测试代码被提交。
JMockit的 mocked标签可以用户拦截自己的代码中引用的代码调用。如下例子
public class TestMain {
@Tested
ControllerTested controller;

@Test
public void testCase(){

}
@Test
public void mockCase(@Mocked
                                 Controller0Mocked mocked){
    new Expectations(){
        {
            mocked.depMockedMeth(anyString);result="hhhhhhhh!!!!";
        }
    };
    System.out.println(controller.print("tetCase----"));
}

}

其中ControllerTested 是我自己的代码逻辑所在类。
Controller0Mocked 是别人提供的类。
ControllerTested print方法 调用 Controller0Mocked depMockedMeth方法。
我在mockCase中使用@Mocked 拦截了Controller0Mocked 的depMockedMeth方法,并让他总是返回”hhhhhhhh!!!!”。那么我的测试就可以正常运行下去了,不用关心如何使用别人的逻辑是否正确。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JMockit is a Java library that provides support for mocking and testing. The @Qualifier annotation is used in JMockit to identify a specific instance of a bean to be used in a test. In Spring, the @Qualifier annotation is used in a similar way to identify a specific bean to be injected into a component. However, in JMockit, the @Qualifier annotation is used in conjunction with other annotations to specify which instance of a mock or spy object to use in a test. For example, consider a scenario where we have two implementations of a service interface and we want to mock one of them for testing. We can use the @Qualifier annotation to identify the bean to be mocked and the @Mocked annotation to create a mock object of that bean. ``` public interface MyService { String getName(); } @Service("fooService") public class FooService implements MyService { @Override public String getName() { return "Foo"; } } @Service("barService") public class BarService implements MyService { @Override public String getName() { return "Bar"; } } public class MyServiceTest { @Test public void testGetName(@Mocked @Qualifier("fooService") MyService fooService, @Mocked @Qualifier("barService") MyService barService) { new Expectations() {{ fooService.getName(); result = "Mocked Foo"; barService.getName(); result = "Mocked Bar"; }}; // Use the mocked instances of fooService and barService in the test // ... } } ``` In the above example, we have two implementations of the MyService interface, FooService and BarService, and we want to mock FooService for testing. We use the @Qualifier("fooService") annotation to identify the bean to be mocked and the @Mocked annotation to create a mock object of that bean. We also create a mock object of the BarService bean using the @Mocked and @Qualifier("barService") annotations. We can then use these mocked instances of the beans in our test.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值