难以测试在构造函数中创建的对象

时间:2020-08-03 03:22:31

标签: java junit mockito jacoco

public counterPublisher() {
try {
ObjectPublisher objPub = new ObjectPublisher.build().port(55).build();
}
catch(SocketException || UnknownHostException) {
Logger.record(“...”);
}





@Test(expected = SocketExcetion)
public void testConst() Throws Exception {

doThrow(new SocketException()).when(ObjectPublisher).build();

counterPublisher cp = new counterPublisher();



// don’t know how to cover this, so I can reach 90% coverage
// I’m getting branch coverage  ratio 0 in jacoco
// could not find an answer online. 

要添加背景信息:我尝试了所有在网上找到的内容,但这些问题均无法解决。我将不胜感激

2 个答案:

答案 0 :(得分:1)

我可以想到三种解决方案:一种是使用powermock,它允许您模拟静态方法。

但是,这不是我的偏好。我个人不喜欢powermock模拟静态或私有方法,因为如果我需要它,这实际上暗示着我的设计需要一些工作。

第二种方法是为ObjectPublisher创建一个工厂,类似于ObjectPublisherFactory。然后,您可以轻松模拟工厂,使其返回模拟ObjectPublish。

// Create a instance of the factory in your class:
private ObjectPublisherFactory factory;

public counterPublisher() {
try {
ObjectPublisher objPub = factory.build(55);
}
catch(SocketException || UnknownHostException) {
Logger.record(“...”);
}

您现在可以使用模拟工厂代替真实工厂,以获得所需的结果。

第三种方法是在您的类中创建一个包私有方法以返回ObjectPublisher

ObjectPublisher getObjectPublisher(int port) {
    return new ObjectPublisher.build().port(port).build();
}

现在,在测试中,您可以将要测试的测试子类化,使getter返回模拟对象。

答案 1 :(得分:0)

这是因为您在方法内部创建了对象。

使用Power Mocktito模拟新实例。

ObjectPublisher objPub = PowerMockito.mock(ObjectPublisher.class);

PowerMockito.whenNew(MyQueryClass.class).withNoArguments().thenReturn(objPub);
doThrow(new SocketException()).when(ObjectPublisher).build();
counterPublisher()// call this method:

此外,请确保在进行u测试时准备好junit。

@PrepareForTest(ClassThatCreatesTheNewInstance.class)//Junit Class annotation.
相关问题