简体   繁体   English

使用通用代码进行Java单元测试

[英]Java unit test with common code

I am new to Java so apologies in advance if this is a silly question. 我是Java的新手,如果这是一个愚蠢的问题,请提前道歉。

I noticed that I'm writing redundant code as my test cases are testing similar behavior with different attributes of same object. 我注意到我正在编写冗余代码,因为我的测试用例正在测试具有相同对象的不同属性的类似行为。

@Test
public void testInvalidA() {
    obj.setA(null)
    //verify exception thrown if A is null
}

@Test
public void testInvalidB() {
    obj.setB(null)
    //verify exception thrown if B is null
}

Is there a way that I could simplify this? 有没有办法可以简化这个?

Thanks! 谢谢!

You can use assertj. 你可以使用assertj。 Example code would be like this, 示例代码是这样的,

@Test
public  void testObjectsAreValid() {
    assertThatExceptionOfType(ExpectedException.class)
        .isThrownBy(obj.setA(null);
    assertThatExceptionOfType(ExpectedException.class)
        .isThrownBy(obj.setB(null);
}

assertj provides direct methods for some common exceptions. assertj为一些常见异常提供直接方法。

assertThatIllegalArgumentException().isThrownBy(() -> obj.setB(null));

Check here for more documentation. 点击此处查看更多文档。 I agree with Dawood though, keep each test separate and clear. 我同意Dawood,保持每个测试分开并清楚。

There's nothing wrong with the way you were doing it -- in fact its preferable most of the time. 你这样做的方式没有任何问题 - 实际上大部分时间都是这样。 But if your example is a simplification of complexity that repeats with a similar testable signature, you could try a bit of functional programming: 但是,如果您的示例是复杂性的简化,并使用类似的可测试签名重复,那么您可以尝试一些函数式编程:

private void nullNotAllowed( Consumer<Object> method ) {
    try {
        method.accept( null );
        fail( "Null Not Allowed");
    }
    catch ( Exception e ) { /*pass*/ }
}

@Test public void nonNullableSetters() {
    YourClass subject = new YourClass();
    nullNotAllowed( subject::setA );
    nullNotAllowed( subject::setB );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM