Using helper methods in the junit class

I want a unit test class, Class A , but it has a dependency on another class that uses the user session method. The method I want to test does not include user session . Can I create a helper method in Class A that replicates the behavior of the Class B method that I need?

I know this is not clear, let them dig out the code to get a clear understanding ....

 public void testDetails() throws Exception { //Some logic that generates DetailsTOList saveDetailsHelper(DetailsTOList); int detailsSize = getDetailsSize(); assertNotNull(detailsSize); } 

Now getDetailsSize() get size information from the database. Class B has this method, but I cannot create a Class B object and test this method, because Class B receives session information from the user, and I can set the session information from the JUnit class.

I created the saveDetailsHelper method, which replicates the behavior of the Class B - saveDetails() method Class B - saveDetails() and calls it in the testDetails() method, as shown above.

My question is:

  • Can we have helper methods in the junit class ?
  • What is best suited to solve this problem?
+4
source share
3 answers

JUnit classes function like any other class in java; You can have helper functions. The only thing that determines whether other functions will be performed (depending on the version of junit), whether or not there are annotations instructing the harness to run it as a test.

However, that is why you should carefully design your classes. If Class B invokes information in a database, this is a great opportunity to share this functionality. You are not specifying the β€œdependency” (are you expanding?), But if Class B is a component of class A, you can create an entire stub class that is a stand for Class B and returns hardcoded (or otherwise encoded) data specifically for testing the class A. As long as the signature of the Class B proxy is the same, you can be sure that Class A is working.

It is often useful to make these inner classes of your test class so that things don't get too messy in your workspace.

 public class testA { @Test public void testDetails { ClassA a = new ClassA(); a.setDependency(new StubClassB()); //run your test } private class StubClassB() extends ClassB { public boolean saveDetails() { //return fake information; } } } 
+3
source

Helper methods will not contain the @Testcase annotation. You should write the test code just like any other code, but will include only the appropriate test methods and check only the relevant parts of this test method.

+1
source

You can put the helper method in the test class, omit the Testcase annotation and call it where necessary (ad hoc for each method or in your setup, if necessary for all tests). But probably the best solution is to use something like JMock to represent class B and return the desired results.

+1
source

Source: https://habr.com/ru/post/1416205/


All Articles