如何为构造函数创建一个测试?

huangapple go评论61阅读模式
英文:

How would you create a test for a Constructor?

问题

我正在为一个已编译程序创建测试,但在获取100%覆盖率方面遇到了问题。

该类的构造函数如下:

public Contact(String name, String email){
     if (name == null){
           throw new IllegalAgrugmentException("name must not be null");
     }
}

我创建的测试如下:

public void testForContactConstructor(){
	Contact testContact = new Contact(null, null);
	assertThrows(IllegalArgumentException.class, () -> {
		testContact.getName();
	});
}

这个测试在Eclipse中没有被覆盖。我该如何解决这个问题?

英文:

I'm creating tests for an already complied program, and I'm having trouble getting 100% coverage.

The constructor for a class is:

public Contact(String name, String email){
     if (name == null){
           throw new IllegalAgrugmentException("name must not be null");
     }
}

The test I created reads:

public void testForContactConstructor(){
		Contact testContact = new Contact(null, null);
		assertThrows(IllegalArgumentException.class, () -> {
			testContact.getName();
		});
	}

The test doesn't get covered in eclispe. How would I fix this?

答案1

得分: 2

你的断言似乎应该是这样的:

assertThrows(IllegalArgumentException.class, () -> {
  contact = new Contact(null, null);
});

否则它会在达到你的断言之前抛出异常 如何为构造函数创建一个测试?

除此之外,我需要更多的信息,你使用的是什么测试框架?可能会缺少一些注解。

总的来说,你可以像这样做(取决于构造函数有多复杂):

public void TestContactConstructorFail(){
    assertThrows(IllegalArgumentException.class, () ->
      new Contact(null, null));
}

public void TestContactConstructorSuccess(){
    Contact c = new Contact(name, email);
    assertNotNull(c); //将其余部分留给 get/set 测试
}

(还可以添加任何特定于框架的注解,例如 Junit 的 @Test

如果构造函数中有复杂的验证或其他内容,我建议将这些内容委托给私有(或类似私有)的方法,并单独对这些方法进行测试。

英文:

Your assertion seems like it should be

assertThrows(IllegalArgumentException.class, () -> {
  contact = new Contact(null, null);
});

Otherwise it will throw before getting to your assert 如何为构造函数创建一个测试?

Other than that i need a little more information, what test framework are you using? There could be annotations missing

All in all you could do something like this (depending on how complex a constructor) :

public void TestContactConstructorFail(){
    assertThrows(IllegalArgumentException.class, () ->
      new Contact(null, null));
}

public void TestContactConstructorSuccess(){
    Contact c = new Contact(name,email);
    assertNotNull(c); //leave the rest for get/set test
}

(add any framework specific annotations as well, e.g. @Test for Junit)

IF you have complex validation or other things in your constructor, i would recommend delegating these to private(ish) methods and testing these separately.

huangapple
  • 本文由 发表于 2020年9月10日 13:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63823262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定