Question

Problem

Compiler gives me a warning at a return line with a message:

Unreachable code detected

Question

How can I refactor my unit test so I don't get compiler warning? Any other feedback is also welcome.

Code

I have a Bar class that wraps WCF calls. If exception happens somewhere inside a call, the wrapper would log an error and throw a WCF fault. Here is the class:

public class Bar
{
    private readonly ILog _execeptionLog;

    public Bar(ILog execeptionLog)
    {
        if (execeptionLog == null) 
            throw new ArgumentNullException("execeptionLog");

        _execeptionLog = execeptionLog;
    }

    public TResult TryExecute<TResult>(Func<TResult> action)
    {
        if (action == null) 
            throw new ArgumentNullException("action");

        try
        {
            return action.Invoke();
        }
        catch (Exception ex)
        {
            _execeptionLog.Error(ex.ToString());
            var fault = FooFault.CreateFrom(ex);
            throw new FaultException<FooFault>(fault);
        }
    }
}

I try to unit test this class to ensure that I get a fault with correct details. Here is my unit test method

[Test]
public void TryExecute_ActionThrowsException_FaultDetailIsNotNull()
{
    //Arrange
    var mock = MockRepository.GenerateMock<ILog>();
    var uut = new Bar(mock);
    var ex = new ArgumentException("foo");

    try
    {
        //Act
        int actual = uut.TryExecute(() =>
        {
            throw ex;
            return 1; //<<<<<<<< Unrechable code detected here
        });
    }
    catch (FaultException<FooFault> fault)
    {
        //Assert
        Assert.IsNotNull(fault.Detail);
    }
}
Was it helpful?

Solution

You could do this...

int actual = uut.TryExecute<int>(() =>
{
    throw ex;
    // return 1; //<<<<<<<< Unrechable code detected here
});

And this is full...

var uut = new Bar(null);
var ex = new ArgumentException("foo");
try
{
    int actual = uut.TryExecute<int>(() =>
    {
        throw ex;
    });
}
catch (Exception fault)
{
    Assert.IsNotNull(fault.Message);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top