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

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

How would you create a test for a Constructor?

问题

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

该类的构造函数如下:

  1. public Contact(String name, String email){
  2. if (name == null){
  3. throw new IllegalAgrugmentException("name must not be null");
  4. }
  5. }

我创建的测试如下:

  1. public void testForContactConstructor(){
  2. Contact testContact = new Contact(null, null);
  3. assertThrows(IllegalArgumentException.class, () -> {
  4. testContact.getName();
  5. });
  6. }

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

英文:

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

The constructor for a class is:

  1. public Contact(String name, String email){
  2. if (name == null){
  3. throw new IllegalAgrugmentException("name must not be null");
  4. }
  5. }

The test I created reads:

  1. public void testForContactConstructor(){
  2. Contact testContact = new Contact(null, null);
  3. assertThrows(IllegalArgumentException.class, () -> {
  4. testContact.getName();
  5. });
  6. }

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

答案1

得分: 2

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

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

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

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

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

  1. public void TestContactConstructorFail(){
  2. assertThrows(IllegalArgumentException.class, () ->
  3. new Contact(null, null));
  4. }
  5. public void TestContactConstructorSuccess(){
  6. Contact c = new Contact(name, email);
  7. assertNotNull(c); //将其余部分留给 get/set 测试
  8. }

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

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

英文:

Your assertion seems like it should be

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

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) :

  1. public void TestContactConstructorFail(){
  2. assertThrows(IllegalArgumentException.class, () ->
  3. new Contact(null, null));
  4. }
  5. public void TestContactConstructorSuccess(){
  6. Contact c = new Contact(name,email);
  7. assertNotNull(c); //leave the rest for get/set test
  8. }

(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:

确定