我认为我对何时如何工作,或者更具体地说是Mockito的工作方式存在基本的误解。
我有一个服务类,该类具有通过构造函数注入的实用程序类。实用程序类还具有其他一些依赖关系,这些依赖关系也由构造函数自动关联。
服务类方法调用实用程序类中的多个方法。该测试在调用的实用程序方法上使用 when / thenReturn 语句。调用service方法时,在使用null参数调用的实用程序方法上获得NPE。但是我希望在何时子句中设置的参数可以设置。下面的代码:
@Service
public class ServiceClass {
private Utility utility;
public ServiceClass(Utility utility) {
this.utility = utility;
}
public serviceMethod(MyDocument myDocument, List<Attachment> attachments) {
SomeType variable1;
OtherType variable2;
List<String> stringList;
long time;
time = utility.method1(variable1, variable2);
stringList = utility.method2(myDocument, attachments.get(0));
...
}
@Service
public class Utility {
private Dependency1 depend1;
private Dependency2 depend2;
public Utility(Dependency1 depend1, Dependency2 depend2) {
this.depend1 = depend1;
this.depend2 = depend2;
}
public long method1(SomeType var1, OtherType var2) {
....
}
public List<String> method2(MyDocument myDoc, Attachment attach) {
....
}
现在测试代码如下:
public TestClass {
private ServiceClass serviceClass;
@Mock
private Depend1 depend1;
@Mock
private Depend2 depend2;
@InjectMocks
private Utility utility;
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Before
public void setup() {
serviceClass = new ServiceClass(utility);
}
@Test
public testServiceMethod() {
long time = System.currentTimeMillis();
MyDocument doc = new MyDocument();
List<Attachments> attachments = Arrays.asList(new Attachment(...), new Attachment(...));
SomeType some = new SomeType();
OtherType other = new OtherType();
when(utility.method1(some, other)).thenReturn(time);
when(utility.method2(doc, attachments.get(0)).thenReturn(Arrays.asList(new String("stg 1"), new String("stg 2"));
String resp = serviceClass.serviceMethod(doc, attachments);
assertEquals("service completed", resp);
}
}
但是,当调用 utility.method2 时, myDocument 显示为空。我原以为它将是MyDocument的一个实例。
我配置不正确吗?我在这里想念一个概念吗?感谢所有帮助!
谢谢。
更新 更正了serviceMethod的参数。
答案 0 :(得分:0)
ServiceClass
是您要测试的类,因此您应该在测试中仅通过@Mock注释此类的依赖项,在这种情况下,请使用utility
属性,删除Depend1
和Depend1
声明。 setup
方法不是必需的,您可以在测试中使用serviceClass
注释@InjectMocks
,它会自动处理注入。最后,您的TestClass
需要@RunWith(MockitoJunitRunner.class)
才能使一切正常运行。
@RunWith(MockitoJunitRunner.class)
public class TestClass{
@InjectMocks
private ServiceClass serviceClass;
@Mock
private Utility utility;
}
这是TestClass的基本定义,测试本身看起来正确,但是可以改进,以在“ ArgumentMatchers
”子句上使用when
并使用{添加一个verify
子句{1}}来验证参数。