且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JUnit4测试用例将无法继续

更新时间:2023-02-17 11:53:37

两个测试用例都在其@Before方法中实例化了一个新的驱动程序;这会以一个新的会话启动一个新的浏览器实例,因此它将丢失任何先前测试用例的已登录会话详细信息:

Both testcases instantiate a new driver in their @Before method; this starts a new browser instance with a fresh session, so it loses the logged-in session details from any previous testcase:

driver = new FirefoxDriver();

我建议您研究两种替代策略:

I'd recommend looking into two alternative strategies:

  1. 每个类一次实例化驱动程序,并将测试用例放入依赖于使用同一会话的同一类中.
  2. 重组您的测试用例,使它们彼此独立.

1.在多个测试用例中保持相同的会话

通过每个类仅实例化一次驱动程序,而不是针对每个测试用例单独实例化驱动程序,可以提高代码执行效率.但是,您应该认为这主要是为了节省效率;我不建议使用它作为将测试用例链接在一起的方式,例如,使测试用例2依赖于成功运行的测试用例1.

1. Keeping the same session across multiple testcases

You can make your code execution more efficient by instantiating the driver only once per class, instead of separately for every testcase. You should think of this as mainly an efficiency saving, however; I don't recommend using it as a way of linking the testcases together so that testcase 2 relies on testcase 1 having run successfully, for example.

总是很想按顺序构造测试用例,因此您要进行测试用例1(例如,包括登录),并自然而然地进入测试用例2(它还要执行一些进一步的操作).但是我警告这会导致问题.这会使您的整个测试套件变得更加脆弱-如果测试用例1中存在问题,则所有随后的测试用例都将失败.它使测试的灵活性降低-您不能只运行测试用例3来单独进行重新测试,也不能从套件中选择单个测试用例.

It's always tempting to construct testcases in sequence, so that you do testcase 1 (which includes logging in, for example) and that leads naturally on to testcase 2 (which does some further actions). However I'd warn that this will lead to problems. It makes your whole test suite more fragile - if there's a problem in testcase 1, all the testcases afterwards fail. It makes your testing less flexible - you can't just run testcase 3 to retest in isolation, and you can't pick and choose individual testcases out of the suite.

我强烈建议您研究第二种策略;因此,例如,如果测试用例1仅在测试登录例程,则使其仅测试登录例程,然后再次注销.而且,如果测试用例2仅测试了一些仅在登录后才能实现的功能-很好,请使其登录,以便可以获取其感兴趣的功能.测试用例1确实也可以登录的事实与测试用例2无关紧要,这也不是问题-实际上,您可以将其视为开始重构测试用例以将重复的代码提取到单独的方法调用中的机会.

I'd strongly recommend you look into the second strategy; so for example if testcase 1 is just testing the login routine, have it just test the login routine and then log out again. And if testcase 2 is just testing some functionality which can only be reached after login - well, make it log in so it can get to the functionality it's interested in. The fact that testcase 1 also does log in is not really relevant to testcase 2, and it's not a problem either - in fact, you can see it as an opportunity to start re-factoring your testcases to extract repeated code into a separate method call.