Questions tagged [junit]
9782 questions
1
votes
1
answer
386
Views
Java JUnit 5 annotations differences
I see there was introduced the new JUnit Jupiter according to JUnit 5 User Guide.
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
I am confused about the same-named annotations I use across the library. Is there any significant difference between these two ones?
org.junit.Test
org.junit.jup...
1
votes
1
answer
68
Views
Parse integer list from Scenario outline's example table in cucumber java
I have to write a BDD test using cucumber with java and I would like to parse an integer list from every line of my example table and pass this list to my step method using the latest version of cucumber (4.2.6).
So I got the following step definition in my feature file:
Scenario Outline: Some scen...
1
votes
1
answer
24
Views
jUnit test doesn't output anything
I am new to jUnit and I am running a test for the output of when the program is run.
My jUnit test is:
class Tests {
private final ByteArrayOutputStream outContent = new
ByteArrayOutputStream();
@BeforeEach
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@AfterEach
public...
1
votes
3
answer
48
Views
java junit exception hadling for code coverage
I am new to java, Junit and jacoco. I am doing exception handling as below. I am catching Exception class as well in case the method throws any other exception that were missed to catch earlier.
private void myMethod1() throws MyCustomException {
....
try {
..... straight JDBC calls for select, inse...
0
votes
1
answer
9
Views
What is the correct assertion to use for an expected value?
I'm learning to use Junit. I wrote a method which generates a number strictly less than xX.
I want to test it using Junit. Not sure which assertion to use as the expected is based on xX and I don't see any comparison assertions.
// within the Junit test class
ClassA a = new ClassA();
@Test
void rand...
1
votes
1
answer
12
Views
How can test MutableLiveData<>.observe when the data is changed?
I have the next code for test if the API is working with Login function:
@RunWith(RobolectricTestRunner.class)
public class LoginTest {
LoginRespository profileRepository = new LoginRespository(RuntimeEnvironment.application);
@Test
public void testLogin() {
MutableLiveData data = new MutableLiveDat...
1
votes
2
answer
1.6k
Views
easymock - mocking to use anyObject as parma of void setter method
Using easymocks, how can I create the mock of following class's process method? I want to create a mock which can accept anyObject of type MyObject.class.
public class Custom {
public void process(MyObject obj){
//code
}
}
I know how to do it if the method returns something, but with void method...
1
votes
1
answer
2.2k
Views
junit.framework.ComparisonFailure: table count expected [1] but was [95]
I'm new to spring and dbunit and have problem with testing my dao layer. The entry is inserted succsessfully, but test ends with failure. Could you help me, please?
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Au...
0
votes
0
answer
2
Views
How to reset env for cucumber-reports through commands in karate
I have one runner file in karate to generate cucumber reports
public void genrateFinalReport() {
System.setProperty('karate.env', 'pre_production'); // ensure reset if other tests (e.g. mock) had set env in CI
Results results = Runner.parallel(getClass(), 1);
generateReport(results.getReportDir());...
1
votes
1
answer
142
Views
Writing unit tests for Java 8 streams
I have a list and I'm streaming this list to get some filtered data as:
List submittedRequestList =
list.stream().filter(Objects::nonNull)
.map(config -> taskExecutorService.submit(() -> requestHandler
.handle(jobId, config))).collect(Collectors.toList());
When I wrote tests, I tried to return some...
1
votes
1
answer
49
Views
H2 database storage mechanism
I have used H2 database for my junit tests and it works perfectly fine.
However, I have few questions regarding it's persistence properties:
What happens when I switch off my laptop? Are the tables and data lost in case of any restart? If yes, is there any restore possible?
Does H2 uses transaction...
1
votes
2
answer
61
Views
JUnit Test Case is not detecting method in controller
New to spring boot.
API in controller looks like,
@RestController('/path1/path2')
public class SomeController
{
@GetMapping('/path3/path4')
public String doSomething()
{
//code goes here
}
}
Test case looks like,
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_POR...
1
votes
2
answer
106
Views
How to continue execution after “NoSuchElementException” in Selenium (Java)?
I'm attempting to create an ArrayList of WebElements from this page:
If all the elements are displayed, they're able to be added to the ArrayList just fine.
ArrayList TodoArray = new ArrayList();
TodoArray.add(todo1);
If I remove one of the elements from the web page(not code) I get this error when...
1
votes
2
answer
108
Views
Testing coroutines in Kotlin
I have this simple test about a crawler that is supposed to call the repo 40 times:
@Test
fun testX() {
// ...
runBlocking {
crawlYelp.concurrentCrawl()
// Thread.sleep(5000) // works if I un-comment
}
verify(restaurantsRepository, times(40)).saveAll(restaurants)
// ...
}
and this implementation:
s...
1
votes
3
answer
46
Views
How to write non-encapsulated unit tests?
I have an autowired variable
@Autowired
private DocumentConfig documentConfig;
I want to make tests for the DocumentService with various states of this configuration object. What are my options? What is the best option?
The first idea is this:
@Test
public void save_failure() {
documentConfig.setNam...
1
votes
3
answer
46
Views
Catching multiple exceptions with Unit Method
I am trying to write a JUnit for my suchAutor() method.
The Problem is that I throw two different Exception and I only know how to handle tests that throw one exception.
public Buch[] suchAutor(String gesuchterName) throws IllegalArgumentException, FileNotFoundException {
if (gesuchterName == '') {...
1
votes
0
answer
111
Views
Having difficulty using SoapUITestCaseRunner in Selenium
Let's get straight to the point:
I'm from QTP/UFT background. My company is transitioning from UFT to Selenium.
We've got Ready API couple of months ago and now I have couple of test cases in ready api. When we run the entire regression suite, we'll have to run the soapui testcases as well as part o...
1
votes
0
answer
183
Views
JUnit define default timeout for category of tests
Let's say I have a FastUnitTests category and I use these annotations to have a test to belong to it:
@Category(FastUnitTests.class)
@Test(timeout = 100)
public void something() {
...
}
I would like to enforce a timeout to every test that is categorized as a fast unit tests. What I need to do, even...
1
votes
1
answer
606
Views
PowerMock not finding PrepareForTest annotation
I am writing test cases for Java classes, and I am using the PowerMock framework for the first time. The dependencies I added to my pom.xml are shown below, along with the full error message. When I tried using the @PrepareForTest annotation in my test class, it did not import anhything. I checked i...
1
votes
1
answer
260
Views
Maven will not find junit tests to execute, says it ran 0 tests and the build succeeded
Firstly, why does maven come with a test goal, but also I see people running mvn surefire:test as if it does something else. What is the difference between the two?
Secondly, I cannot seem to get maven to run my unit tests. No matter what I try, I always get Results : Tests run: 0, Failures: 0, Erro...
1
votes
0
answer
1k
Views
Processing of multipart/form-data request failed. Stream ended unexpectedly while running junit test case for servlet
I am writing multipart file upload test case in servlet but it is throwing exception as mention:
Code:
public class MessageUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory =...
1
votes
1
answer
799
Views
How to test Spring Rest Controller with Mockito.when if controller has HttpServletRequest injected in method
My Controller looks like this
@GetMapping('/networks/{networkId}')
public Resource getNetwork(
@PathVariable('networkId') UUID id,
HttpServletRequest request) {
Resource network = networkClient.getNetwork(id);
network.removeLinks();
network.add(LinkHelper.getNetworkObjectLinkArray(request, id));
ret...
1
votes
1
answer
1.8k
Views
Spring Boot testing java.lang.IllegalStateException: Failed to load ApplicationContext and missing bean
I seem to have got myself into a loop of trying to fix this.
I thought a bean was missing so I'd @MockBean the name of the class it said it was missing, run it again and it would say another class is missing.
The classes it's erroring over aren't even the ones I'm testing. Why is this happening?
I k...
1
votes
1
answer
372
Views
VSTS Maven build - no JUnit tests run
[Update: Problem cause found! read below]
Problem: VSTS Maven build does not seem to run JUnit, does not show any JUnit results, does not seem to produce any JUnit testreports.
In VSTS, we have a Java project with a Contact and TestContact class with 1 testcase;
source\module\src\main\java\nl\custom...
1
votes
1
answer
253
Views
Is it possible to parameterized test with arquillian ressources?
I'm writing integration tests and I would like to know if it's possible to use Arquillian with parameterized test.
In JUnit4 I have to specify @RunWith(parameterized.class) to run parameterized tests but in this case baseURL and browser are not initialized.
@RunWith(Parameterized.class)
public class...
1
votes
0
answer
104
Views
Run JUnit 4 Tests Twice With Different Configuration
I have collection of JUnit test classes currently. I would like to run all the tests I currently have but with different configurations.
So for instance in my code I have a class:
public class Storage {
public static final int VERSION = 1;
}
and I would like to run all my unit tests with Storage.VER...
1
votes
2
answer
1.5k
Views
Mock an object inside a method in JUnit
I'm trying to get to grips with JUnit & Mockito etc.
I currently have a method with the below line.
ObjectMetadata metadata = getMetadata(path.toString());
Is there any way I can mock it? I've tried things like the below
Whitebox.setInternalState(, 'metadata', 'abc');
but I just get
org.powermock.r...
1
votes
1
answer
69
Views
Error: Could not find or load main class junit_runner.JgrRunner
I'm trying to run a JUnit test on some of my files. I'm pretty sure that I have JUnit installed and configured, but something in the configuration is incorrect. I think it has to do with the fact that I'm using a machine running Ubuntu. Here's my main file:
import java.util.ArrayList;
public class A...
1
votes
1
answer
907
Views
How configure WireMock to use https (and a random port)?
I tried to set wiremock to run https on a random port:
@Rule
public WireMockRule wireMockServer = new WireMockRule(
WireMockConfiguration.wireMockConfig().dynamicPort().dynamicHttpsPort()
);
but when I use this and I call wireMockServer.httpsPort() I get the exception:
java.lang.IllegalStateExceptio...
1
votes
2
answer
134
Views
Junit test - Eclemma Coverage in Jackson toString
I want to have 100% coverage on the method toString overriden with Jackson JSON.
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
return '';
}
}
I can make...
1
votes
1
answer
156
Views
Can I run a JUnit test Case as “multiple tests” by different parameters?
@RunWith(Theories.class)
public class ExampleTest {
@Theory
@Test
public void isEven(int value)
{
assertEquals(value%2,0);
}
public static @DataPoints int[] values = valueBuilder();
private static int[] valueBuilder(){
int[] returnValue= {1,2,3,4,5,6,7,8,9,10};
return returnValue;
}
}
I was able to...
1
votes
1
answer
110
Views
How to save the number of successful JUnit Cucumber scenarios to TeamCity variable from bat file run
I have a bat file that is running my JUnit Cucumber tests. This bat file is being invoked by TeamCity. Once the JUnit Cucumber tests have been run, the output more or less ends with:
[15:24:37]18 Scenarios (18 passed)
[15:24:37]187 Steps (187 passed)
[15:24:37]0m24.339s
How can I save the line '18 S...
1
votes
1
answer
450
Views
Running adb command using selenium in java
I want to execute the ADB(android debug bridge) command in selenium using Java. Later I need to use my Junit test for executing a script on AWS(Amazon web service) device farm. How to do it ?
Please find my Junit test case below,In this code i had simulated the test case, I want to get the memory an...
1
votes
1
answer
266
Views
Robolectric not handling getApplicationContext() correctly - NPE
I've been running some tests on an android application using Robolectric and it's been working well until now.
My application passes the result of getApplicationContext() to a constructor, but Robolectric should be ensuring the value of this is not null as I am using the BuildActivity() method. The...
1
votes
0
answer
129
Views
How to mock a public method inside a final class
I am trying to mock a public method inside a final class . My problem is that as I am not able to create the object of that final class , I am not able to spy it . Below is the method inside my class .
public final class Method extends Executable {
@CallerSensitive
public Object invoke(Object obj, O...
1
votes
0
answer
290
Views
Unable to find instrumentation info for: ComponentInfo{../android.support.test.runner.AndroidJUnitRunner}
I have written a simple Android instrumental test case to test networking operation.
Test case class name: Main3ActivityTest.java
Method name:addNewEmployee
I run my test case using command line then I got following exception.
Command:
./adb -s emulator-5554 shell am instrument -w -r -e class murali...
1
votes
1
answer
228
Views
Jax RS & Jersey with Junit; Test case is ignored
I can't get Jersey to work with Junit. Can anyone help here? I don't know what else to do.
I'm using my tomcat server, and when I run the project, I right-click the folder and select 'run on server.' After this is done, I am able to use a post-client in my web browser to use the web service and it w...
1
votes
0
answer
382
Views
Maven fails with spring boot, junit 5, kotlin
I have a Kotlin Spring Boot application and using JUnit 5 for test.
When i build project in Idea - it successfully builds.
When i run test in Idea - all tests passes.
When i run test with mvn test - all tests runs and passes.
When i run mvn spring-boot:run - application successfully starts.
But when...
1
votes
3
answer
1.9k
Views
Mock a private method [duplicate]
This question already has an answer here:
How to mock private method for testing using PowerMock?
4 answers
I have a method which is private . Now, I do not want to call this private method while doing unit test on execute() method. I have tried with PowerMockito and all, but with all type of mocki...
1
votes
0
answer
456
Views
How to invoke ApplicationContextInitializer in junit of spring-boot application
I am new to spring-boot and implemented a simple application with dynamic entity filtering based on squiggly. Everything works fine except I am unable to make a junit to test that functionality. I tested a lot of solutions found on the web but none works.
My application is initialized as proposed in...