Showing Not Covered by Test if method throw exception junit mockito - unit-testing

implementation class have two method :
test method call by test case and inside test() i call test2() which is throw exception, now I want
to
cover this method by test case but in sonar it showing not covered by test , so how i can covered this
method:
[service implementation class][1]
public void test()throws SystemException {
LOGGER.info("Testing exception");
test2(); //not covered by test
LOGGER.info("Testing exception 2");//not covered by test
System.out.print("hi");//not covered by test
}
public void test2() throws SystemException {
LOGGER.info("Testing exception");
throw new SystemException();
}
Test case: this is test which is call service.test1() method but in code coverage it is showing not
covered by test:
#Test(expected = SystemException.class)
public void test1() throws SystemException {
service.test();
}

You're being very unclear about what exactly your problem is. When you refer to "this method" or "it", you have to be clear about exactly what that means.
Concerning your existing code, if you're wondering how to "cover" the last two lines of method "test", it's not possible to cover them. In fact, it's not at all possible to execute those lines at all. If method "test2" throws that exception, it will exit method "test2" along with method "test" without executing the rest of method "test".
To be clearer about what you're asking, you might try changing your method names to be a little more different, and refer to those method names explicitly.

Related

How to stop / kill my current test case?

I want to stop the execution of a test if it matches a certain scenario in order to avoid code duplication.
Consider the following situation:
CoreProviderTest
public void executeCoreSuccess(Object responseModel){
assertNotNull("Response successful", responseModel != null);
if (responseModel == null) {
//Kill Test
}
}
ChildProviderTest - extends CoreProviderTest
#Test
public void responseTester() {
new Provider().getServiceResponse(new Provider.Interface() {
#Override
public void onSuccess(Object responseModel) {
executeCoreSuccess(responseModel);
//Continue assertions
}
#Override
public void onFailure(ErrorResponseModel error) {
executeCoreFailure(error);
}
});
}
For a null response, I would like to kill my current test case inside CoreProviderTest otherwise that might trigger exceptions in further assertions. I wanted to avoid something like:
CoreProviderTest
if (responseModel == null) {
return true;
}
ChildProviderTest
#Override
public void onSuccess(Object responseModel) {
if (executeCoreSuccess(responseModel))
return;
//Continue assertions
}
Is there a way to kill the current test execution with Mockito, JUnit or Roboletric? No luck so far googling an answer.
Thanks in advance
If you are using JUnit5, it has features like Assumtions, Disabling tests and Conditional Test Execution.
Here's the link :
https://junit.org/junit5/docs/current/user-guide/#writing-tests-assumptions
In your case, looks like assumingThat should work. Here's the API :
https://junit.org/junit5/docs/5.0.0/api/org/junit/jupiter/api/Assumptions.html#assumingThat-boolean-org.junit.jupiter.api.function.Executable-
JUnit Assumptions suits perfect to the given case.
Code snippet now stands like:
CoreProvider
public void executeCoreSuccess(Object responseModel){
assumeTrue("Response successful",responseModel != null);
}
According to JUnit's documentation:
A failed assumption does not mean the code is broken, but that the
test provides no useful information. Assume basically means "don't run
this test if these conditions don't apply". The default JUnit runner
skips tests with failing assumptions.
+1 Adelin and Dossani

How to unit test method with if else and no return conditions

I have a method with following code:
public void myMethod() {
if (condition1) {
doSomething1();
if (condition2) {
doSomething2();
} else {
doSomething3();
}
}
}
Now doSomething1, doSomething2, doSomething3 are void methods.
How to unit-test myMethod ?
eg: if condition1 is satisfied check if doSomething1 was called.
Is there something we can do to refactor this to make easily testable ?
A general approach could be 3 test cases. Each test case would exercise a single condition. For each test case:
doSomethingX would be patched with a test object, (there are mock libraries for pretty much all languages)
conditionX would be triggered
doSomethingX would execute
test would assert that doSomethingX was actually called
There are many strategies for removing the need to mock.
if doSomethingX is an instance method then you could create a test specific subclass and override doSomethingX and make your assertion in the subclass.
You could also refactor your method to require the caller to inject the doSomethingX dependency (dependency injection)
public void myMethod(somethingStrategy)
Then the test could easily configure a mock object and call myMethod with the mock object.
Dependency injection could take place on the class level by having the class be instantiated with a somethingStrategy as well.
(a) The fact that these methods return void means their outcome is irrelevant, we just don't care. But you need to test the outcome, and need therefore to know the outcome. So this is a huge red flag that the code isn't SOLID and needs refactoring.
(b) Hey, this could be legacy code that is impossible to change, so if your methods truly are voids, then the following refactoring could help, if you then assert that the myNewMethod2 and doSomething2/3 are called once / not called at all depedndant upon the conditions (e.g. via MOQ unit testing framework)
public myNewMethod()
{
bool cnd1 = (condition1);
bool cnd2 = (condition2);
if(cnd1)
{
myNewMethod2(cnd2);
}
}
public myNewMethod2(bool cnd2)
{
doSomething1();
myNewMthod3(cnd2);
}
public myNewMethod3(bool cnd2)
{
if (cnd2)
{
doSomething2();
}
else
{
doSomething3();
}
}
(c) Another strategy for voids, which I'm not a great fan of, but leaves your original code largely intact, is this:
public void myMethod() {
try
{
if (condition1) {
doSomething1();
if (condition2) {
doSomething2();
} else {
doSomething3();
}
}
catch(Exception ex)
{
//
}
}
Your unit test can then assert that no exception is thrown. Not ideal, but if needs must...

PHPUnit test code inside catch block

I have a Symfony controller using try...catch.
I use phpunit to test my application. I have searched but havent found a way how to test the code inside a catch exception. How can I force php unit to pretend that something went wrong and enters the catch block and test this as well?
ie:
try {
$foo = 1;
} catch (\Exception $ex) {
$mail = new Mail();
$mail->sendMail();
return new Response();
}
How can I tell phpunit to throw an \Exception so it will test code inside catch block of above?
Well, under those conditions, it will obviously not throw any exceptions, but consider the function your try/catch lies within. You need to unit test that function, and provide arguments that will cause it to fail, and catch.
For instance:
public function doStuff($argument) {
try {
$parsed = (int)$argument; //but what if $argument is a string with letters
} catch (\Exception $ex) {
//do stuff
}
To test that an exception is thrown when you mess it up:
public function testDoStuff() {
// get a mock of the class, let's just call it $mock
// do some regular asserts if you want
$this->setExpectedException('\Exception');
$mock->doStuff("haha, you can't parse this");
}
If you really have some complex stuff in your catch block you can move it to separate protected method of the controller and test it separately. You can easily access protected method outside of its class using reflection.

Catching exception in Googletest Setup()

I have a test class which contains SetUp() and TearDown(), with certain inputs and is run with a variety of different inputs. When certain inputs are used, an exception will be thrown within SetUp() rather than in the body. This is expected and though it is not strictly part of the test, I would prefer not to have to move my SetUp() code into the body of the test just for this specific instance. However, I can't find a way of catching the exception here. My code is similar to the following:
struct MyInputs {
int first_;
const char* second_;
const char* third_;
};
The test class is pretty standard gtest boilerplate:
class MyTestClass : public ::testing::TestWithParam<MyInputs> {
public:
virtual void SetUp();
virtual void TearDown() {};
// etc...
}
void MyTestClass::SetUp() {
// Do some stuff here using MyInputs.first_ which may throw
// a "thrown from here" exception
}
I have a standard test closure though it's irrelevant to the problem here really - it doesn't get this far.
TEST_P(MyTestClass,aSpecificTest) {
// ... some stuff ...
}
Then I create the loop with multiple inputs:
INSTANTIATE_TEST_CASE_P(MultipleTests,
MyTestClass,
::testing::Values( MyInputs( 1234, "ABC", "XXX"), // <-- No exception thrown
MyInputs( 5678, "DEF", "ZZZ") ) ); // <-- Exception thrown
When I run the code, I get the error:
C++ exception with description "thrown from here" thrown in SetUp().
when it hits the 'bad' input. Is there a way I can catch this and either ignore or set an EXPECT_ type clause? I realise that I can simply put a try/catch in the SetUp(), but was rather hoping that I could use EXPECT_THROW somewhere to incorporate into the test.

NSubstitute conditions for throwing exception other than parameters

I'm using NSubstitute to mock a class that my method under test uses. This mocked class may throw a particular exception under certain conditions.
The method that I'm testing has some "retry" logic that it executes when it catches this exception. I'm trying to test this retry logic. So, I need a particular method of this mocked class to throw the exception sometimes, but not other times. Unfortunately, the method that throws this exception has no parameters, so I can't base the throw logic on parameters.
How can I make the mocked object's method throw the exception either:
A) ...the first N times it's called
or
B) ...based on the parameters some other method that's called before it
or
C) ...under any other condition other than the parameters passed in
To give you a clearer picture of what I'm trying to do, my code is something like:
IDataSender myDataSender = GetDataSender();
int ID = GetNextAvailableID();
myDataSender.ClearData();
myDataSender.Add(ID,"DataToSend");
bool sendSuccess = false;
while (!sendSuccess)
{
try
{
myDataSender.SendData();
sendSuccess = true;
}
catch (IDCollisionException)
{
ID++;
MyDataSender.ClearData();
myDataSender.Add(ID,"DataToSend");
}
}
So, I need to test my retry logic, and I need to simulate that IDCollisionException. However, I can't have the SendData() throwing the exception every single time, or the retry loop will never succeed.
What can I do here?
If I understand the question correctly, you can use When..Do and close over a local variable to get this behaviour.
const int throwUntil = 3;
var callsToSendData = 0;
var dataSender = Substitute.For<IDataSender>();
dataSender
.When(x => x.SendData())
.Do(x =>
{
callsToSendData++;
if (callsToSendData < throwUntil)
{
throw new DbCollisionException();
}
});
Similarly, you can also use callbacks to locally capture parameters passed to other methods, and access them within the Do block (rather than just using a counter).