如何模拟在使用JMokit测试的方法中创建的本地对象

时间:2019-05-31 15:25:51

标签: java junit mocking junit4 jmockit

我无法模拟正在尝试测试的方法中创建的Class的实例。下面是一个说明问题的示例。

正在测试的类和方法:

// class being used in the class to be tested
public class SomeOtherClass{

public ResponseObject addObject(Request dtoObject){
    /// Some business logic goes here

    return reponseObject;
  }
} 

// Class to be tested
public class ClassToBeTested {

public ClassToBeTested() {}

public void myMethodToBeTested() {
    SomeOtherClass otherClassObject = new SomeOtherClass();

    // Here I want mock the otherClassObject and also addObject method 
    // Eventhoug I mocked it seems to me that as otherClassObject is being created here locally 
    // I am unable to mock it.
    ReponseObject reponseObject = otherClassObject.addObject(dtoObject);

    // do some other stuff using the reponseObject
  }
}

测试类别:

public class TestClassToBeTested {
@Tested private ClassToBeTested classBeingTested;
@Injectable SomeOtherClass innerSomeOtherClass;

RequestObject myRequestObject = new RequestObject();
myRequestObject.setSomevalue1("1");
myRequestObject.setSomevalue2("2");

ResponseObject myMockResponseObject = new ResponseObject();
myMockResponseObject.setResultCode(SUCCESS);

@Test
public void shouldTestSomething() {
    new NonStrictExpectations(){{
        // Here I am returning the mocked response object.
        SomeOtherClass.addObject((SomeOtherClass)any);
        result =myMockResponseObject;
    }};   

    classBeingTested.myMethodToBeTested(); 

    // ... 
 }
}

我模拟了SomeOtherClass及其方法,但是没有运气,不确定使用JMockit模拟它的正确方法。

  

SomeOtherClass及其方法addObject

即使我在Test类中对其进行了嘲笑,但在要测试的方法中也将其清除。我发现有人问HERE类似的问题,但是该解决方案使用了其他一些单元测试框架Mockito。我正在努力寻找使用JMokcit的类似解决方案。有人可以帮我找到解决方案吗?

2 个答案:

答案 0 :(得分:0)

您只需为此使用@Mocked。查看JMockit tutorial或API文档,有很多示例。

答案 1 :(得分:0)

再次尝试并调试后,我发现出了问题。我做错的是在模拟接口(IService),因此无法正常工作。当我将其更改为模拟实现的类(OtherService)时,它可以正常工作。

因此在Test类中,我替换了

@Mocked IService otherService;

@Mocked OtherService otherService;

此更改后,我的问题得到解决。

谢谢