gpt4 book ai didi

java - 使用 Mockito 对基于 Guice 的类进行单元测试

转载 作者:行者123 更新时间:2023-12-02 11:55:18 28 4
gpt4 key购买 nike

我的应用程序使用 Google Guice 依赖注入(inject)框架。我现在无法找到为我的类(class)编写单元测试的方法。

private final Person aRecord;

@Inject
public MyClass(Venue venue, @Assisted("record") Record myRecord) {
super(venue,myRecord);
aRecord = (Person) myRecord;
}

public void build() throws Exception {
super.build();
super.getParentRecord().setJobType(aRecord.getJobType());
super.getParentRecord().setHairColor(aRecord.getHairColor());
super.getParentRecord().setEyeColor(aRecord.getEyeColor());
}

我想为子类中的build()方法编写单元测试,应该

  • 确保当调用 super.build() 时,会填充 super.getParentRecord() 上的所有基本信息,例如年龄、性别等
  • 确保如果 aRecord.getJobType() 为 null,则在 build() 方法中引发异常
  • 确保如果 aRecord.getHairColor() 为 null,则在 build() 方法中引发异常
  • 确保如果 aRecord.getEyeColor() 为 null,则在 build() 方法中引发异常

最佳答案

您有两个 MyClass 依赖项(Venue 和 Record),因此您必须模拟它们。

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
...
Venue venueMock = mock(Venue.class);
Record recordMock = mock(Record.class);

然后在单元测试中,您必须创建 MyClass 的实例并断言预期结果:

例如:“如果 aRecord.getJobType() 为 null,请确保在 build() 方法中引发异常”

@Test(expected=RuntimeException.class)// or whatever exception you expect
public void testIfExceptionIsThrownWhengetJobTypeReturnsNull() throws Throwable {
Venue venueMock = mock(Venue.class); //create the mocks
Record recordMock = mock(Record.class);//create the mocks
when(recordMock.getJobType()).thenReturn(null); //specify the behavior of the components that are not relevant to the tests

MyClass myClass = new MyClass(venueMock, recordMock);
myClass.build();
//you can make some assertions here if you expect some result instead of exception
}

请注意,如果您没有指定任何模拟依赖项的返回值(使用 when()),它将返回返回类型的默认值 - 对于对象为 null,对于对象为 0原始数字, boolean 值为 false 等。因此最好对 MyClass 中使用的所有方法进行 stub 。

关于java - 使用 Mockito 对基于 Guice 的类进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47651600/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com