[英]About unit-test dependency
I'm trying to code some basic unit-tests for a project I am currently working on where I have my service that has a method addPlaneModel
to add a plane model (under the hood it adds a PlaneModel
instance into a TreeMap
and throws a custom exception if the TreeMap
already contains the key).我正在尝试为我目前正在从事的项目编写一些基本的单元测试,我的服务有一个方法
addPlaneModel
来添加平面 model (在引擎盖下它将PlaneModel
实例添加到TreeMap
并抛出自定义如果TreeMap
已经包含键则异常)。
I could write a test (for example shouldAddNewPlane_Succeed
) to see if it's properly adding the PlaneModel
but my problem comes if I wanted to create a test to see if the PlaneModel
already existed (for example shouldAddNewPlane_ThrowExistingModelException
because I should call addPlaneModel
twice to make it throw the exception, but if shouldAddNewPlane_Succeed
test doesn't run first, I don't really 'know' if that method works as it should.我可以编写一个测试(例如
shouldAddNewPlane_Succeed
)来查看它是否正确添加了PlaneModel
但是如果我想创建一个测试来查看PlaneModel
已经存在(例如shouldAddNewPlane_ThrowExistingModelException
因为我应该调用addPlaneModel
两次以使其抛出例外,但如果shouldAddNewPlane_Succeed
测试没有首先运行,我真的不知道该方法是否可以正常工作。
I've read that unit-tests should be independant from each other but I can't really grasp how to do it in this case, do I necessarily have to run them in order?我读过单元测试应该彼此独立,但我无法真正掌握在这种情况下如何做到这一点,我是否必须按顺序运行它们?
If you want to execute some common code before running a test, you can use the @Before
method annotation in JUnit.如果要在运行测试之前执行一些常用代码,可以使用 JUnit 中的
@Before
方法注解。 For instance:例如:
@Before
public void init() {
LOG.info("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
This code will always execute before any other test that you run.此代码将始终在您运行的任何其他测试之前执行。 This is useful to define a certain order for execution to your tests.
这对于定义执行测试的特定顺序很有用。
You should be creating a new instance of the class you are testing before each test.您应该在每次测试之前创建您正在测试的 class 的新实例。
So your test class will look like:因此,您的测试 class 将如下所示:
class MyTests {
private MyService myService;
@Before // junit 4, or @BeforeEach for junit 5
public void setup() {
myService = new MyService(... pass mocks of dependencies ...);
}
@Test
public void aTest() {
myService...
}
@Test
public void aTest2() {
myService... // this is a fresh instance of MyService, any changes to the
// state of the instance used in aTest() are gone.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.